Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Highligh the max and min value in a column pandas

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading