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.
CodePudding user response:
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
df1 = df.style.apply(red_or_auto, axis=None, subset=['v', 'key'])
df1