12

Is it possible to define a color of a specific cell in a pandas dataframe based on integer position like for instance df.iloc[1,1] with pandas styling? https://pandas.pydata.org/pandas-docs/stable/style.html

Something like the following would be nice, but is not working.

def style_specific_cell(val):

    color = 'lightgreen'
    val.iloc[2, 8] = color
    return XYZ

df = df.style.applymap(style_specific_cell, subset=['Column1']

1 Answer 1

12

Use style.Styler.apply with helper DataFrame of styles:

def style_specific_cell(x):

    color = 'background-color: lightgreen'
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    df1.iloc[2, 8] = color
    return df1

df.style.apply(style_specific_cell, axis=None)

pic

Sample DataFrame:

df = pd.DataFrame({
        'A':list('abcdef'),
         'B':[4,5,4,5,5,4],
         'C':[7,8,9,4,2,3],
         'D':[1,3,5,7,1,0],
         'E':[5,3,6,9,2,4],
         'F':list('aaabbb')
})
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for your answer! I tried your solution but unfortunately, the cell will not be colored in my case. I will add a screenshot to my question.
@blackrafi - sorry, few times was answer modify, check if use last version ;)
@blackrafi - need color = 'background-color: green', not only green
One additional question: If I want to color several cells in a dataframe, how would this work?
Thx, I used df5.iloc[[2,8], [2,2]] = color
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.