Skip to content
Advertisement

Pandas DataFrame Style for this condition

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.

Advertisement

Answer

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

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