The Wayback Machine - https://web.archive.org/web/20240717024753/https://www.geeksforgeeks.org/highlight-the-negative-values-red-and-positive-values-black-in-pandas-dataframe/
Open In App

Highlight the negative values red and positive values black in Pandas Dataframe

Last Updated : 20 Aug, 2020
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Let’s see various methods to Highlight the positive values red and negative values black in Pandas Dataframe.
First, Let’s make a Dataframe:

Python3




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


Output: 

Now, come to the highlighting part. Our objective is to highlight negative values red and positive values black.

Method 1: Using Dataframe.style.apply().

Syntax: DataFrame.style.apply(self, func, axis=0, subset=None, **kwargs)
Parameters: 

  • func: It should take a pandas.Series or pandas.DataFrame based on the axis and should return an object with the same shape. 
  • axis: {0 or ‘index’, 1 or ‘columns’, None}, default 0. Apply to each column (axis=0 or ‘index’), to each row (axis=1 or ‘columns’), or to the entire DataFrame at once with axis=None. 
  • subset: Set of columns or rows on which you want to call the func. 
  • **kwargs: Pass along to func.

Returns: Styler object.

Example 1: Highlighting text.

Python3




# Define a function for colouring 
# negative values red and 
# positive values black
def highlight_max(s):
    if s.dtype == np.object:
        is_neg = [False for _ in range(s.shape[0])]
    else:
        is_neg = s < 0
    return ['color: red;' if cell else 'color:black' 
            for cell in is_neg]
  
# Using apply method of style 
# attribute of Pandas DataFrame
df.style.apply(highlight_max)


Output: 

 

Example 2: Highlighting cells instead of text.

Python3




# Define a function which 
# returns the list for 
# df.style.apply() method
def highlight_max(s):
    if s.dtype == np.object:
        is_neg = [False for _ in range(s.shape[0])]
    else:
        is_neg = s < 0
    return ['background: red; color:white' 
            if cell else 'background:black; color:white' 
            for cell in is_neg]
  
# Using apply method of style 
# attribute of Pandas DataFrame
df.style.apply(highlight_max)


Output: 

 

Method 2: Using dataframe.style.applymap() method.

Syntax: DataFrame.style.applymap(self, func, subset=None, **kwargs)
Parameters: 

  • func: It takes a scalar value and return the scalar values 
  • subset: Set of columns or rows on which you want to call the func. 
  • **kwargs: Pass along to func.

Returns: Styler object.

Example 1: Highlighting text.

Python3




# Define a function for 
# colouring negative values 
# red and positive values black
def highlight_max(cell):
    if type(cell) != str and cell < 0 :
        return 'color: red'
    else:
        return 'color: black'
  
df.style.applymap(highlight_max)


Output: 

 

Example 2: Highlighting cells instead of text.

Python3




# Define a function which 
# returns string for 
# applymap() method
def highlight_max(cell):
    if type(cell) != str and cell < 0 :
        return 'background: red; color:black'
    else:
        return 'background: black; color: white'
  
df.style.applymap(highlight_max)


Output: 

 Note: pandas.DataFrame.applymap() method passes only single cell into the callable function while the pandas.DataFrame.apply() passes the pandas.Series to the callable function.

Reference: Styling in Pandas
 



Similar Reads

Highlight the nan values in Pandas Dataframe
In this article, we will discuss how to highlight the NaN (Not a number) values in Pandas Dataframe. NaN values used to represent NULL values and sometimes it is the result of the mathematical overflow.Lets first make a dataframe: C/C++ Code # Import Required Libraries import pandas as pd import numpy as np # Create a dictionary for the dataframe d
2 min read
Replace negative values with latest preceding positive value in Pandas DataFrame
In this article, we will discuss how to replace the negative value in Pandas DataFrame Column with the latest preceding positive value. While doing this there may arise two situations - Value remains unmodified if no proceeding positive value existsValue update to 0 if no proceeding positive value exists Let's discuss these cases in detail. Case 1:
3 min read
Highlight Pandas DataFrame's specific columns using applymap()
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 functi
2 min read
Highlight Pandas DataFrame's specific columns using apply()
Let us see how to highlight specific columns of a Pandas DataFrame. We can do this using the apply() function of the Styler class. Styler.apply() Syntax : Styler.apply(func, axis = 0, subset = None, **kwargs) Parameters : func : function should take a Series or DataFrame (depending on-axis), and return an object with the same shape. Must return a D
2 min read
How to sum negative and positive values using GroupBy in Pandas?
In this article, we will discuss how to calculate the sum of all negative numbers and positive numbers in DataFrame using the GroupBy method in Pandas. To use the groupby() method use the given below syntax. Syntax: df.groupby(column_name) Stepwise Implementation Step 1: Creating lambda functions to calculate positive-sum and negative-sum values. p
3 min read
Red Black Tree in Python
Red Black Tree is a self-balancing binary search tree where each node has an extra bit representing its color, either red or black. By constraining how nodes are colored during insertions and deletions, red-black trees ensure the tree remains approximately balanced during all operations, allowing for O(log⁡n) search, insert, and delete operations.
11 min read
How to Drop Negative Values in Pandas DataFrame
Handling data effectively is crucial in data analysis and manipulation. One common task is cleaning the data by removing negative values, especially when they are considered outliers or invalid entries. The Pandas library in Python offers several efficient methods to accomplish this. This article will provide three good examples of how to drop nega
3 min read
Highlight the maximum value in last two columns in Pandas - Python
In this article, we will discuss how to highlight the maximum values in Pandas Dataframe. Let's first make a dataframe: Example: C/C++ Code # 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, 2
2 min read
Highlight the maximum value in each column in Pandas
Let's discuss how to highlight the maximum values in Pandas Dataframe. Lets first make a dataframe: Example: C/C++ Code # Import Required Libraries import pandas as pd import numpy as np # Create a dictionary for the dataframe dict = {'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, 45, 21, 22], 'Mar
2 min read
Highlight the minimum value in each column In Pandas
In this article, we will discuss how to Highlight the minimum values in Pandas Dataframe. So, Let's first make a dataframe: C/C++ Code # 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, 4
3 min read
three90RightbarBannerImg