hernanavella
hernanavella

Reputation: 5552

Custom styling pandas dataframe

The documentation shows an example, on how to change the font color of an element conditional on value, which works fine as expected:

def color_negative_red(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    """
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color

s = df.style.applymap(color_negative_red)

My question is how to implement a function that instead applies the font color change in the whole row?

Upvotes: 4

Views: 340

Answers (1)

jezrael
jezrael

Reputation: 862641

You working with DataFrame, so it set row to red if at least one value is less as 0 in row:

def color_negative_red(x):
    c1 = 'background-color: red'
    c2 = 'background-color: black'

    df1 = pd.DataFrame(c2, index=x.index, columns=x.columns)
    df1 = df1.where((x > 0).all(axis=1), c1)
    return df1

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

Upvotes: 4

Related Questions