Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Highlight the maximum value in last two columns in Pandas – Python

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In this article, we will discuss how to highlight the maximum values in Pandas Dataframe. Let’s first make a dataframe:
 Example:

Python3




# Import Required Libraries
import pandas as pd
import numpy as np
  
# Create a dictionary for the dataframe
dict = {'Name': ['Sumit Tyagi', 'Sukritin', 'Akriti Goel',
                 'Sanskriti', 'Abhishek Jain'],
        'Age': [22, 20, np.nan, np.nan, 22],
        'Marks': [90, 84, 33, 87, 82]}
  
# Converting Dictionary to Pandas Dataframe
df = pd.DataFrame(dict)
  
# Print Dataframe
df

Output: 
 

Now, come to the highlighting part. Our objective is to highlight cells with maximum values in last 2 columns.
 

Method 1: Highlighting Cell with maximum value in last 2 columns

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
  • axis: (0/1) based on which axis you want to find the maximum.

Example:

Python3




# Highlighting the maximum values 
# of last 2 columns
df.style.highlight_max(subset = ['Age', 'Marks'],
                       color = 'lightgreen', axis = 0)

Output: 
 

 

Method 2: Instead of using column names we generalise it to last two columns

Example:

Python3




# Highlighting the maximum values of
# last 2 columns
df.style.highlight_max(subset = df.columns[-2:],
                       color = 'lightgreen', axis = 0)

Output: 
 

 

Method 3: Highlighting the text instead of cell

Example: 

Python3




# Defining custom function which returns
# the list for df.style.apply() method
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, subset = df.columns[-2:])

Output: 
 

 

Method 4: Highlighting cell with maximum values

Example: 

Python3




# Defining custom function which returns
# the list for df.style.apply() method
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, subset = df.columns[-2:])

Output: 
 

 


My Personal Notes arrow_drop_up
Last Updated : 26 Jul, 2020
Like Article
Save Article
Similar Reads
Related Tutorials