Custom style pandas dataframe

The documentation shows an example of how to change the font color of an element conditionally to a value that works just 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 font color change in the entire line?

+4
source share
1 answer

You work with DataFrame, so it sets the string to red, if at least one value is less than 0the string:

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)
+4
source

Source: https://habr.com/ru/post/1690231/


All Articles