Highlight the maximum value in each column in Pandas
Last Updated :
28 Jul, 2020
Let’s discuss how to highlight the maximum values in Pandas Dataframe. Lets first make a dataframe:
Example:
Python3
import pandas as pd
import numpy as np
dict = { 'Name' : [ 'Sukritin' , 'Sumit Tyagi' , 'Akriti Goel' ,
'Sanskriti' , 'Abhishek Jain' ],
'Age' : [ 22 , 20 , 45 , 21 , 22 ],
'Marks' : [ 90 , 84 , 33 , 87 , 82 ]}
df = pd.DataFrame( dict )
df
|
Output:
Now, come to the highlighting part. Our objective is to highlight cells with maximum values in each column.
Method 1: Highlighting Cell with maximum value in each column
We will do this by using the highlight_max() method of DataFrame property. highlight_max() method takes 3 arguments, subset = name of the columns of which you want to find the maximum, color = name of the color with which you want to highlight the cell and axis = (0/1) based on which axis you want find the maximum.
Python3
df.style.highlight_max(color = 'lightgreen' , axis = 0 )
|
Output:
Method 2: Highlighting the text instead of cell
Python3
def highlight_max(s):
is_max = s = = s. max ()
return [ 'color: green' if cell else '' for cell in is_max]
df.style. apply (highlight_max)
|
Output:
Method 3: Highlighting cell with maximum values
Python3
def highlight_max(s):
is_max = s = = s. max ()
return [ 'background: lightgreen' if cell else '' for cell in is_max]
df.style. apply (highlight_max)
|
Output:
Method 4: Highlighting cell with maximum values but not highlighting the string values
Python3
def highlight_max(s):
if s.dtype = = np. object :
is_max = [ False for _ in range (s.shape[ 0 ])]
else :
is_max = s = = s. max ()
return [ 'background: lightgreen' if cell else '' for cell in is_max]
df.style. apply (highlight_max)
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...