Skip to content
Advertisement

Pandas Styler Subset column by values

I’m using the following to color the cells in a dataframe:

import seaborn as sns

cm1 = sns.diverging_palette(h_pos=130, h_neg=10, s=99, l=55, n=99, as_cmap=True)

df_s = (df.style
    .background_gradient(cmap=cm1, subset=['col1']))

This successfully applies the background gradient to the values in col1

However, I’d like to something like the following:

df_s = (df.style
    .background_gradient(cmap=cm1, subset=['col1'] < x))

Which does not work

The idea is to only apply the gradient to values in col1 which are less than x, and display the full dataframe where col1 >= x is un-colored.

Seems like there should be an easy way to do this but I can’t seem to get the argument into the right format for subset.

Thanks in advance for the help!

Advertisement

Answer

You need to use pd.IndexSlice:

import seaborn as sns

cm1 = sns.diverging_palette(h_pos=130, h_neg=10, s=99, l=55, n=99, as_cmap=True)
np.random.seed(123)
df = pd.DataFrame(np.random.randint(0,100,(5,5)), columns=[*'ABCDE'])
df.style.background_gradient(cmap=cm1, subset=pd.IndexSlice[df['C']<50, 'C'])

Output:

enter image description here

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement