pd.style.apply using multiple conditions to style a dataframe

Viewed 173
my_df = pd.DataFrame({'name': ['John', 'Jorge', 'Igor'], 'rank2020':[2,1,3], 'rank2021':[1,3,2], 'change':[1,-2,1]})

I wish to style the change in red font, but at the same time apply a prefix of '+' to the positive values.

To get the red font I can:

my_df.style.apply(lambda x: np.where(x>0, 'color:red',''), subset='change')

however, I cannot add a prefix of + to the positive values, while retaining the red font. I can do this of course without pd.style, but in that case I lose the styler object and only have the '+' prefix without any red font.

How can I have both '+' for positive number and red font?

Thanks

1 Answers

We can chain format after applying colouring:

my_df.style.apply(
    lambda x: np.where(x > 0, 'color:red', ''),
    subset='change'
).format('{:+d}', subset='change')

Or with a lambda if needing more complex transformations:

my_df.style.apply(
    lambda x: np.where(x > 0, 'color:red', ''),
    subset='change'
).format(
    lambda x: f'+{x}' if x > 0 else x,
    subset='change'
)

enter image description here

Related