How to highlight a row in Pandas Data frame in Python

In this tutorial, we are going to learn how to highlight a row in Pandas Dataframe in Python. To achieve this, we use apply() function of the Styler class.

Styler.apply() function

Syntax:

Styler.apply(func,axis=0,subset=None,**kwargs)

Parameters:

  • func: func should take a Series if axis in [0,1] and return a list-like object of same length, or a Series, not necessarily of same length, with valid index labels considering subsetfunc should take a DataFrame if axis is None and return either an ndarray with the same shape or a DataFrame not necessarily of the same shape, with valid index and columns labels considering subset.
  • axis: It applies to each column if the value is 0 or ‘index’, to each row if the value is 1 or ‘columns’ or to the entire Dataframe if given ‘None’. The default value is 0.
  • subset: It is an optional parameter used to limit data to before applying the function.
  • **kwargs: dict which is passed along to the function.

Returns: Styler

Let’s go through some examples,

Example 1:

import pandas as pd
data = pd.DataFrame({"A" : [ 5, 23, 56, 7, 8],
                "B" : [ 2, 43, 52, 68, 6],
                "C" : [ 41, 5, 7, 2, 32],
                "D" : [ 14, 3, 16, 2, 36],
                "E" : [ 45, 23, 66, 32, 23]})

print("Original DataFrame :")
display(data)
def highlight_rows(x):
    if x.E>40:
        return['background-color: pink']*5
    else:
        return['background-color: blue']*5
print("Highlighted DataFrame :")
display(data.style.apply(highlight_rows, axis = 1))

Output:

Pandas Dataframe

In the above example, we are highlighting the rows which have the value of column ‘E’ greater than 40. To do so, we are writing a function that returns background-color multiplied by 5, as there are five columns in the data frame. This function is passed to the apply function of the styler class.

Example 2:

import pandas as pd
dt = pd.DataFrame({"Roll_number" : [ 23, 5, 14, 37],
                "Name" : ["Sara","Mukesh","Naina","Anand"],
                   "Score":[ 35, 46, 52, 37]})
print("Original DataFrame :")
display(dt)
def highlight_rows(x):
    if x.Roll_number>20 and x.Score<40:
        return['background-color: red']*3
    else:
        return['background-color: yellow']*3
print("Highlighted DataFrame :")
display(dt.style.apply(highlight_rows, axis = 1))

Output:

In this example, we are taking multiple conditions for highlighting a row. They all can be written in a single line using ‘and’ keyword. Since we need to color the whole row, we are going to multiply the return statement by 3.

You may also learn,

One response to “How to highlight a row in Pandas Data frame in Python”

  1. Anonymous says:

    What is display()? You should provide working examples.

Leave a Reply

Your email address will not be published. Required fields are marked *