3

So I figured out how to color singular cells and coloumns using the Style module in pandas. How ever, I want to color entire rows based on values in a singler cell in that row.

For instance, if a cell C in coloumn A has the value 23, color C's row in yellow.

How do I that?

oyed
  • 739
  • 2
  • 7
  • 18

1 Answers1

7

Use:

df =  pd.DataFrame({'A':[23,25,10], 'B':[7,8,3], 'C':[8,3,1]})
print (df)
    A  B  C
0  23  7  8
1  25  8  3
2  10  3  1

def highlight_col(x):
    #copy df to new - original data are not changed
    df = x.copy()
    #set by condition
    mask = df['A'] == 23
    df.loc[mask, :] = 'background-color: yellow'
    df.loc[~mask,:] = 'background-color: ""'
    return df    

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

picture

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Cool, can you explain what exactly happens here: df.loc[mask, :] = 'background-color: red' df.loc[~mask,:] = 'background-color: ""' – oyed Nov 24 '17 at 08:59
  • It set values to DataFrame by conditions. `:` means set all columns if mask is `True`. so for second set need `~` for inverse mask. – jezrael Nov 24 '17 at 09:01
  • Thank you, ~ was new to me. – oyed Nov 24 '17 at 09:05