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.

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Sharvari Gc
  • 691
  • 1
  • 11
  • 25

1 Answers1

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

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • 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 "` Should I ask a different question for it? @jezrael – Sharvari Gc Apr 21 '18 at 09:38
  • @SharvariGc - Can you explain more? The best is create new question or modify old with sample data and expected output. thanks. – jezrael Apr 21 '18 at 09:39
  • Have asked [link](https://stackoverflow.com/questions/49954454/dataframe-styling-based-on-conditions-for-groups-of-columns) @jezrael – Sharvari Gc Apr 21 '18 at 09:53
  • @SharvariGc - thank you. So second mask is `b = df[['D','E']].eq(df['D'], axis=0)` ? – jezrael Apr 21 '18 at 09:54