w3resource

Pandas styling Exercises: Write a Pandas program to highlight the negative numbers red and positive numbers black


1. Highlight Negative/Positive Values

Create a dataframe of ten rows, four columns with random values. Write a Pandas program to highlight the negative numbers red and positive numbers black.

Sample Solution :

Python Code :

import pandas as pd
import numpy as np
np.random.seed(24)
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)
print("Original array:")
print(df)
def color_negative_red(val):
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color
print("\nNegative numbers red and positive numbers black:")
df.style.applymap(color_negative_red)

Original array:

Original array:
      A         B         C         D         E
0   1.0  1.329212 -0.770033 -0.316280 -0.990810
1   2.0 -1.070816 -1.438713  0.564417  0.295722
2   3.0 -1.626404  0.219565  0.678805  1.889273
3   4.0  0.961538  0.104011 -0.481165  0.850229
4   5.0  1.453425  1.057737  0.165562  0.515018
5   6.0 -1.336936  0.562861  1.392855 -0.063328
6   7.0  0.121668  1.207603 -0.002040  1.627796
7   8.0  0.354493  1.037528 -0.385684  0.519818
8   9.0  1.686583 -1.325963  1.428984 -2.089354
9  10.0 -0.129820  0.631523 -0.586538  0.290720

Negative numbers red and positive numbers black:

Sample Output:

Python Pandas: pandas styling exercise-1 output

Download the Jupyter Notebook from here.


For more Practice: Solve these Related Problems:

  • Write a Pandas program to highlight negative values in red and positive values in black for a dataframe with random numbers.
  • Write a Pandas program to apply conditional styling that marks positive numbers black and negatives red, using a custom formatting function.
  • Write a Pandas program to color-code cells based on sign: red for negatives, black for zero and positives, and test it on a randomly generated dataframe.
  • Write a Pandas program to create a style function that highlights negative entries in a dataframe with red text while keeping positive numbers unchanged.

Go to:


Previous: Python Pandas Style Home.
Next: Create a dataframe of ten rows, four columns with random values. Convert some values to nan values. Write a Pandas program which will highlight the nan values.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.