简体   繁体   中英

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!

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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM