How to use DataFrame.style property In Python

  • df.style.set_properties: By using this, we can use inbuilt functionality to manipulate data frame styling from font color to background color.

Python3




# Importing the necessary libraries -->
import pandas as pd
import numpy as np
 
# Seeding random data from numpy
np.random.seed(24)
 
# Making the DataFrame
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4),
                                 columns=list('BCDE'))], axis=1)
 
# DataFrame without any styling
print("Original DataFrame:\n")
print(df)
print("\nModified Stlying DataFrame:")
df.style.set_properties(**{'background-color': 'black',
                           'color': 'green'})


Output: 

df.style.set_properties

  • df.style.highlight_null : With the help of this, we can highlight the missing or null values inside the data frame.

Python3




# Replacing the locating value by NaN (Not a Number)
df.iloc[0, 3] = np.nan
df.iloc[2, 3] = np.nan
df.iloc[4, 2] = np.nan
df.iloc[7, 4] = np.nan
 
# Highlight the NaN values in DataFrame
print("\nModified Stlying DataFrame:")
df.style.highlight_null(null_color='red')


Output: 

df.style.highlight_null

  • df.style.highlight_min :  For highlighting the minimum value in each column throughout the data frame.

Python3




# Highlight the Min values in each column
print("\nModified Stlying DataFrame:")
df.style.highlight_min(axis=0)


Output: 

df.style.highlight_min

  • df.style.highlight_max : For highlighting the maximum value in each column throughout the data frame.

Python3




# Highlight the Max values in each column
print("\nModified Stlying DataFrame:")
df.style.highlight_max(axis=0)


Output: 

df.style.highlight_max

Set Pandas dataframe background Color and font color in Python

As we know, the basic idea behind styling is to make more impactful for the end-user readability. We can make changes like the color and format of the data visualized in order to communicate insight more efficiently. For the more impactful visualization on the pandas DataFrame, generally, we DataFrame.style property, which returns styler object having a number of useful methods for formatting and visualizing the data frames.

Similar Reads

Using DataFrame.style property

df.style.set_properties: By using this, we can use inbuilt functionality to manipulate data frame styling from font color to background color....

Using User-defined Function

...

Using Seaborn Library

...