Apply function to single row in order to highlight cells based on condition

Viewed 136

I want to highlight the cells in the last row of my df, and only the last row, if the cell value is greater than 20.

My df is structured similar to this. There are 43 cols and 4 rows where the first col Name are strings and the rest are numbers

 |Name | A  |  B | C  |
---------------------
0|ID1  | 1  | 2  | 3  |
1|ID1  | 4  | 5  | 6  |
2|ID1  | 7  | 8  | 9  |
3|Diff | 25 | 19 | 40 | 

For the numbers in row Diff only I want to highlight the ones that are greater than 20. So the output would be

 |Name | A  |  B | C  |
---------------------
0|ID1  | 1  | 2  | 3  |
1|ID1  | 4  | 5  | 6  |
2|ID1  | 7  | 8  | 9  |
3|Diff | **25** | 19 | **40** | 

I've tried

df.iloc[-1,:].style.apply((lambda x: 'background-color : red' if x>20 else ''), axis=1)

But I get series has no attribute style.

I can't set the Name as the index because the IDs are the same and you can't apply style to duplicate indexes.

This works but it colors all of the cells greater than 20 and it doesn't print the Name column which I need

def color_PercentDiff(df):
    s = pd.DataFrame('', index=dummy.index, columns=dummy.columns)
    s[df>20] = 'background-color : red'
    return s

df.iloc[:,1:].style.apply(color_PercentDiff, axis=None)
1 Answers

Use pd.IndexSlice

def color_PercentDiff(df):
    s = pd.DataFrame('', index=df.index, columns=df.columns)
    s[df>20] = 'background-color : red'
    return s

subs =pd.IndexSlice[[df.last_valid_index()], df.columns[1:]]
res = df.style.apply(color_PercentDiff, axis=None, subset=subs)

OR

subs =pd.IndexSlice[[df.last_valid_index()], df.columns[1:]]
res = df.style.apply(lambda x: np.where(x>20, 'background-color : red', ''), axis=1, subset=subs)

res:

enter image description here

Related