Home > Enterprise >  Highligh the max and min value in a column pandas
Highligh the max and min value in a column pandas

Time:12-18

I need to highlight maximum value and minimum value for certain columns in pandas. Maximum - green Color Mininmum - Red Color Input Dataframe :

   Name  A  B
0   A    1  4
1   B    2  5
2   C    3  6

Expected Output:

enter image description here

CodePudding user response:

If use pandas version above 1.3.0 use:

(df.style.highlight_max(axis=0, props='background-color:green;', subset=['A','B'])
         .highlight_min(axis=0, props='background-color:red;', subset=['A','B'])
         .to_excel('styled.xlsx', engine='openpyxl'))

If use oldier versions:

def highlight_min_max(x):
    c1 = 'background-color: green'
    c2 = 'background-color: red'
    # condition
    m1 = x.eq(x.max())
    m2 = x.eq(x.min())
    # empty DataFrame of styles
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)

    # set columns by conditions
    return df1.mask(m1, c1).mask(m2, c2)

df.style.apply(highlight_min_max, axis=None, subset=['A','B'])

Alternative:

def highlight_max(s, props=''):
    return np.where(s == np.nanmax(s.values), props, '')

def highlight_min(s, props=''):
    return np.where(s == np.nanmin(s.values), props, '')

(df.style.apply(highlight_max, axis=0, props='background-color:green;', subset=['A','B'])
         .apply(highlight_min, axis=0, props='background-color:red;', subset=['A','B'])
         .to_excel('styled.xlsx', engine='openpyxl'))
  • Related