1

How can I use df.style for subsets of a DataFrame based on this given condition?

df = DataFrame({'A':[3,4,5],'B':[9,10,15],'C':[3,4,5]})
df
    A   B   C
0   3   9   3
1   4   10  4
2   5   15  1

df1 = df.eq(df.iloc[:, 0], axis=0)
df1
     A       B       C
0   True    False   True
1   True    False   True
2   True    False   True

I want to highlight the cells in which it is False. But make changes to df, not just df1

Have edited the question. It is different from the previous questions because they are only dealing with element-wise coloring. But I want to color based the above condition.

1
  • Have edited my question. Sorry for the previous question. @Wen Commented Apr 21, 2018 at 4:40

1 Answer 1

2

You need create DataFrame of background-colors with style.Styler.apply:

def highlight(x):
    c1 = 'background-color: red'
    c2 = '' 
    m = x.eq(x.iloc[:, 0], axis=0)
    df1 = pd.DataFrame(c2, index=x.index, columns=x.columns)
    #add color red by False values 
    df1 = df1.where(m, c1)
    return df1

df.style.apply(highlight, axis=None)

pic

Sign up to request clarification or add additional context in comments.

4 Comments

How to apply a styling for different subsets of the dataframe on the same above condition? I need to compare groups of columns and style where there is inequality. I couldn't concatenate two cannot concatenate object of type "<class 'pandas.io.formats.style.Styler'> Should I ask a different question for it? @jezrael
@SharvariGc - Can you explain more? The best is create new question or modify old with sample data and expected output. thanks.
Have asked link @jezrael
@SharvariGc - thank you. So second mask is b = df[['D','E']].eq(df['D'], axis=0) ?

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.