Home > Software design >  pandas color cell based on value of other column
pandas color cell based on value of other column

Time:03-16

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 ?

CodePudding user response:

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)
  • Related