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

Analyzing data is a fundamental aspect of any data science task. One common requirement during data exploration is to visually highlight negative and positive values in a pandas DataFrame for effective interpretation.

In this article, we will explore powerful techniques using the Pandas library in Python to visually highlight negative values in red and positive values in black within a DataFrame. By employing these approaches, data analysts can efficiently distinguish between positive and negative trends, aiding in insightful data interpretation.

Methods to Highlight Values

There are several methods to highlight negative values in red and positive values in black within a Pandas DataFrame. Here are three commonly used techniques ?

Method 1: Using Styler.applymap()

The Styler class in Pandas allows us to apply formatting to DataFrame elements. We define a formatting function that checks the sign of each value and returns appropriate CSS styles ?

import pandas as pd

def highlight_values(x):
    if x < 0:
        return 'color: red'
    else:
        return 'color: black'

# Create sample DataFrame
data = {'A': [-2, 4, -1, 5, 0],
        'B': [3, -6, 2, 7, -4],
        'C': [-3, -2, 1, 6, -5]}
df = pd.DataFrame(data)

# Apply styling
styled_df = df.style.applymap(highlight_values)
print("Original DataFrame:")
print(df)
Original DataFrame:
   A  B  C
0 -2  3 -3
1  4 -6 -2
2 -1  2  1
3  5  7  6
4  0 -4 -5

Method 2: Using Conditional Formatting with apply()

We can create a custom function that returns CSS styles for each column based on value conditions ?

import pandas as pd

def color_negative_red(val):
    color = 'red' if val < 0 else 'black'
    return f'color: {color}'

# Create sample DataFrame
data = {'Sales': [-100, 250, -50, 300, 0],
        'Profit': [50, -80, 120, 180, -25],
        'Growth': [-5, 10, -2, 8, 3]}
df = pd.DataFrame(data)

# Apply conditional formatting
styled_df = df.style.applymap(color_negative_red)
print("DataFrame with conditional formatting applied:")
print(df)
DataFrame with conditional formatting applied:
   Sales  Profit  Growth
0   -100      50      -5
1    250     -80      10
2    -50     120      -2
3    300     180       8
4      0     -25       3

Method 3: Using Background Gradient

The background_gradient() method applies gradient colors based on values, with custom color mapping for positive and negative values ?

import pandas as pd

# Create sample DataFrame
data = {'Temperature': [-10, 5, -3, 15, 0],
        'Pressure': [2.5, -1.2, 3.8, -0.5, 1.1]}
df = pd.DataFrame(data)

# Apply background gradient with custom colors
styled_df = df.style.background_gradient(cmap='RdYlBu_r', axis=None)

print("DataFrame for gradient styling:")
print(df)
print("\nNote: Gradient colors will be visible in Jupyter notebooks or when exported to HTML/Excel")
DataFrame for gradient styling:
   Temperature  Pressure
0          -10       2.5
1            5      -1.2
2           -3       3.8
3           15      -0.5
4            0       1.1

Note: Gradient colors will be visible in Jupyter notebooks or when exported to HTML/Excel

Comparison of Methods

Method Best For Customization Performance
applymap() Simple color coding High Good for small data
apply() with conditions Column-wise formatting Very High Better for larger data
background_gradient() Visual gradients Medium Built-in optimization

Practical Example

Here's a complete example showing how to highlight financial data ?

import pandas as pd

def highlight_financial_data(x):
    if x < 0:
        return 'color: red; font-weight: bold'
    elif x > 0:
        return 'color: green; font-weight: bold'
    else:
        return 'color: gray'

# Financial data example
financial_data = {
    'Q1_Revenue': [1000, -500, 750, 0, 1200],
    'Q2_Revenue': [-200, 800, -100, 500, 900],
    'Net_Profit': [150, -300, 50, -50, 200]
}

df_financial = pd.DataFrame(financial_data, 
                           index=['Company_A', 'Company_B', 'Company_C', 'Company_D', 'Company_E'])

styled_financial = df_financial.style.applymap(highlight_financial_data)
print("Financial Data with Highlighting:")
print(df_financial)
Financial Data with Highlighting:
           Q1_Revenue  Q2_Revenue  Net_Profit
Company_A        1000        -200         150
Company_B        -500         800        -300
Company_C         750        -100          50
Company_D           0         500         -50
Company_E        1200         900         200

Conclusion

Using Pandas styling methods like applymap() and background_gradient(), you can effectively highlight negative values in red and positive values in different colors. These techniques provide powerful visual cues for data analysis and help identify trends quickly in your datasets.

Updated on: 2026-03-27T07:48:46+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements