Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas color cell based on value of other column

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading