Home > database >  Python pandas - highlight top n max,min values
Python pandas - highlight top n max,min values

Time:08-06

How can I highlight top 3 max (or min) values in dataframe column? For example I have:

import pandas as pd
df = pd.DataFrame({"Values A":[1,2,3,4,5], "Values B":[5,4,3,2,1]})

and I want to highlight (I want to be able to choose color for background and text) top 3 values in column Values A. How can I do that?

CodePudding user response:

You can do this with df.style.apply and a custom function (or a lambda) with the logic. Kindly try:

def custom_style(v, props=''):
    return props if v < df.sort_values('Values A',ascending=False)['Values A'].values[2] else None
df_styled = df2.style.applymap(custom_style, props='color:red')

Edit: To show top 5 values in the dataframe, you can simply use:

def custom_style(v, props=''):
    return props if v > np.reshape(df2.values, (1,df2.shape[0]*df2.shape[1]))[4] else None
df_styled = df2.style.applymap(custom_style, props='color:red')

CodePudding user response:

Try this,

def format_color_groups(x):
    if x.name<3:
        return ['background-color: yellow', ''] 
df = df.sort_values('Values A')
df.style.apply(format_color_groups, axis=1)

Change colors as your requirement.

  • Related