1

I am working on a jupyter notebook right now and I am looking for a way to conditionally color each cell in a pandas dataframe according to its relative value within the column (or alternatively row).

The final output should be a pandas dataframe.
Conceptually it would be like creating a heatmap where the shading is defined independently for each column and is based on the max and min of the column itself.

I have had a look at this and this but in both they create actual plot as output instead of coloring the dataframe cells.

CAPSLOCK
  • 6,243
  • 3
  • 33
  • 56

2 Answers2

6

You can find more options here: Pandas DataFrame Styling: Builtin Styles

import seaborn as sns
cm = sns.light_palette("green", as_cmap=True)

df.style.background_gradient(cmap=cm, axis=0) # explicitly applying column-wise

The output will look like:
enter image description here

CypherX
  • 7,019
  • 3
  • 25
  • 37
2

You can use the style method. The output looks like a dataframe, but is not.
If you want each column to have a color gradient corresponding to the values of the column:

df.style.background_gradient()

To apply the style row-wise, use the additional parameter axis=1.

CAPSLOCK
  • 6,243
  • 3
  • 33
  • 56
Horace
  • 1,024
  • 7
  • 12