Jeff Tilton
Jeff Tilton

Reputation: 1296

Pandas Styling using conditionals

I am trying to color table cells dependent on values in another column.

import pandas as pd
df = pd.DataFrame({'a':[1,2,3],'b':[1.5,3,6],'c':[2.2,2.9,3.5]})
df

    a   b   c
0   1   1.5 2.2
1   2   3.0 2.9
2   3   6.0 3.5

For example, in the above df I want b colored red if c>b. So the cell df[0,b] would be highlighted, but none of the others.

I have made multiple attempts, but in general what I have looks like the below

def highlight(val1,val2):
    color = 'red' if val1 < val2 else 'black'
    return 'color: %s' % color

df.style.apply(lambda x: highlight(x.data.b,x.data.c), axis = 1,subset=['b'])

TypeError: ('memoryview: invalid slice key', 'occurred at index 0')

I do not see any examples in the documentation. They are generally using conditionals on a single column such as highlighting a max or min within a column or the entire df.

Maybe what I want is not currently possible? From the documentation:

Only label-based slicing is supported right now, not positional.

If your style function uses a subset or axis keyword argument, consider wrapping your function in a functools.partial, partialing out that keyword.

Upvotes: 4

Views: 2447

Answers (1)

jezrael
jezrael

Reputation: 862406

You need return DataFrame of colors for set styles. So need create new df with same index and columns with default values - here background-color: red and then change values by condition:

def highlight(x):
    c1 = 'background-color: red'
    c2 = 'background-color: black' 
    #if want set no default colors 
    #c2 = ''  
    m = x['c'] > x['b'] 
    df1 = pd.DataFrame(c2, index=x.index, columns=x.columns)
    df1.loc[m, 'b'] = c1
    return df1

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

one

two

Upvotes: 6

Related Questions