3

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!

1 Answer 1

2

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

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.