1

I want to make a conditional formatting, which is applied on another column in a pandas dataframe.

ID v key
1 -1 XYz
2 4 ABC
3 -5 FFF
4 6 34S

So I want to change the font-color to red in column "key", if value in column "v" is greater than 0.

1 Answer 1

2

Define a highlighter function and color values conditionally.

import numpy as np
import pandas as pd
def red_or_auto(x):
    # set font color to red for keys whose corresponding v is positive
    # all other values have default font color
    return pd.DataFrame('', index=x.index, columns=x.columns).assign(key=np.where(x['v']>0, "color:red", ''))

# apply the highlighter function red_or_auto to 'v' and'key' columns of df
df_styled = df.style.apply(red_or_auto, axis=None, subset=['v', 'key'])
df_styled

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

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.