Jd Baba
Jd Baba

Reputation: 6118

Python Pandas styling changing background color of whole row based on value in column

I would like to change the background color to green, yellow and red based on the lastupdate column below:

Reproducible code:

testdf = pd.DataFrame({'title': {0: 'Test1',
  1: 'Test2',
  2: 'Test3',
  3: 'Test4',
  4: 'Test5',
  5: 'Test6',
  6: 'Test7',
  7: 'Test8'},
 'url': {0: 'link',
  1: 'link',
  2: 'link',
  3: 'link',
  4: 'link',
  5: 'link',
  6: 'link',
  7: 'link'},
 'status': {0: 'In_progress',
  1: 'In_progress',
  2: 'In_progress',
  3: 'In_progress',
  4: 'In_progress',
  5: 'In_progress',
  6: 'In_progress',
  7: 'In_progress'},
 'age': {0: 12, 1: 14, 2: 31, 3: 42, 4: 81, 5: 104, 6: 105, 7: 138},
 'lastupdate': {0: 6,
  1: 18,
  2: 20,
  3: 20,
  4: 20,
  5: 19,
  6: 90,
  7: 111}})

Data:

    title   url status  age lastupdate
0   Test1   link    In_progress 12  6
1   Test2   link    In_progress 14  18
2   Test3   link    In_progress 31  20
3   Test4   link    In_progress 42  20
4   Test5   link    In_progress 81  20
5   Test6   link    In_progress 104 19
6   Test7   link    In_progress 105 90
7   Test8   link    In_progress 138 111

The logic for green, yellow, red is as follows:

def highlight(s):
    '''
    highlight the maximum in a Series yellow.
    '''
    if s <= 14: 
        return 'background-color: green'
    elif (s > 14 & s < 30):
        return 'background-color: yellow'
    elif s > 30:
        return 'background-color: red'

I am struggling to apply to the testdf. I can use testdf.style.apply but it tends to apply to the whole table. Is there a way to modify this function and apply on one column and change the background of all the rows ?

The output should look as follows:

enter image description here

Eventually I will use this to send email.

Upvotes: 1

Views: 3389

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150805

Since you use lastupdate to determine the whole row, you want to apply on row and return the format css for each cell. Something like this:

def highlight(row):
    '''
    highlight the maximum in a Series yellow.
    '''
    s = row['lastupdate']
    if s <= 14: 
        css = 'background-color: green'
    elif (14 < s < 30):
        css = 'background-color: yellow'
    else:
        css = 'background-color: red'

    return [css] * len(row)

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

Output:

enter image description here

Upvotes: 3

Related Questions