Mary
Mary

Reputation: 1142

Using pandas style to give colors to some rows with a specific condition

This is the output of pandas in excel format:

Id      comments     number
1       so bad        1
1       so far        2
2       always        3
2       very good     4
3       very bad      5
3       very nice     6
3       so far        7
4       very far      8
4       very close    9
4       busy          10

I want to use pandas to give a color (for example: gray color) to rows that their value for Id column is even. For example rows 3 and 4 have even Id numbers, but rows 5, 6 and 7 have odd Id numbers. Is there any possible way to use pandas to do it?

Upvotes: 1

Views: 8164

Answers (1)

wkzhu
wkzhu

Reputation: 1660

As explained in the documentation http://pandas.pydata.org/pandas-docs/stable/style.html what you basically want to do is write a style function and apply it to the style object.

def _color_if_even(s):
    return ['background-color: grey' if val % 2 == 0 else '' for val in s]

and call it on my Styler object, i.e.,

df.style.apply(_color_if_even, subset=['id'])

Upvotes: 1

Related Questions