1

I have an arbitrary dataframe, something like this:

import pandas as pd
df = pd.DataFrame.from_dict({'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd'], 'col_3':[100,-100, 50, -50,]})
df

Sample picture of dataframe

is there a way to change the formatting for each item in such a way that larger values within a column are one color and smaller values are another? Preferably the implementation would be:

  • something brief
  • able to be applied to most simple dataframes
  • robust enough to handle different datatypes

as an example, Excel has conditional formatting which looks like this:

excel conditional formatting

It doesn't do anything meaningful with strings or chars, but otherwise behaves nicely

Warlax56
  • 1,170
  • 5
  • 30

1 Answers1

1

Like many amazing things, you can do it with seaborn

this:

import pandas as pd
df = pd.DataFrame.from_dict({'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd'], 'col_3':[100,-100, 50, -50,]})

import seaborn as sns
cm = sns.light_palette("green", as_cmap=True)
s = df.style.background_gradient(cmap=cm)
s

makes this:

formatted table

Warlax56
  • 1,170
  • 5
  • 30