5

I would like to color in red cells of a DataFrame on one column, based on the value of another column.

Here is an example:

df = pd.DataFrame([
  { 'color_A_in_red': True , 'A': 1 },
  { 'color_A_in_red': False , 'A': 2 },
  { 'color_A_in_red': True , 'A': 2 },
])

should give: colored_df

I know how to color a cell of a df in red but only based on the value of this cell, not the value of another cell:

df_style = df.style
df_style.applymap(func=lambda x: 'background-color: red' if x == 2 else None, subset=['A'])
df_style

wring_color_df

Is there a way to color cells of a DataFrame based on the value of another column ?

1 Answer 1

5

Use custom function for DataFrame of styles is most flexible solution here:

def highlight(x):
    c = f"background-color:red" 
    #condition
    m = x["color_A_in_red"]
    # DataFrame of styles
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    # set columns by condition
    df1.loc[m, 'A'] = c
    return df1


df.style.apply(highlight, axis=None)
Sign up to request clarification or add additional context in comments.

3 Comments

How to remove color_A_in_red column after adding style attribute when exporting to excel for example. For me it gives error message.
@Michael - do you need hide ?
I have used hide option but it doesn't work for me for some reason.

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.