Related Articles

Related Articles

Highlight Pandas DataFrame’s specific columns using applymap()
  • Last Updated : 17 Aug, 2020

Let us see how to highlight elements and specific columns of a Pandas DataFrame. We can do this using the applymap() function of the Styler class.

Styler.applymap() 

Syntax : Styler.applymap(self, func, subset = None, **kwargs)

Parameters :

  • func : takes a scalar and returns a scalar.
  • subset : valid indexer to limit data to before applying the function.
  • **kwargs : dict pass along to func.

Returns : Styler

Let’s understand with examples:



First of all create a simple data frame:

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas as pd 
import pandas as pd 
  
# creating the dataframe  
df = pd.DataFrame({"A" : [14, 4, 5, 4, 1], 
                   "B" : [5, 2, 54, 3, 2],
                   "C" : [20, 20, 7, 3, 8],
                   "D" : [14, 3, 6, 2, 6]}) 
  
print("Original DataFrame :")
display(df)

chevron_right


Output :

Example 1 : For every cell in the DataFrame, if the value is less than 6 then we will highlight the cell with red color, otherwise with blue color.

filter_none

edit
close

play_arrow

link
brightness_4
code

# function definition
def highlight_cols(s):
    color = 'red' if s < 6 else 'blue'
    return 'background-color: % s' % color
  
# highlighting the cells
display(df.style.applymap(highlight_cols))

chevron_right


Output :

Example 2 : This time we will highlight only the cells in some specified columns.

filter_none

edit
close

play_arrow

link
brightness_4
code

# function definition
def highlight_cols(s):
    return 'background-color: % s' % 'yellow'
  
# highlighting the cells
display(df.style.applymap(highlight_cols, 
                          subset = pd.IndexSlice[:, ['B', 'C']]))

chevron_right


Output :

Highlight specific columns with the help of Indexing:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

df.style.applymap(highlight_cols, subset = pd.IndexSlice[:, ['B', 'C']])

chevron_right


Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :