2

I have this DataFrame:

import pandas as pd
df = pd.DataFrame({'2021-04': {'2021-04': 100.0, '2021-05': float("nan"), '2021-06': float("nan")},
 '2021-05': {'2021-04': 9.599326432568967, '2021-05': 100.0, '2021-06': float("nan")},
 '2021-06': {'2021-04': 7.952995602884856,
  '2021-05': 5.549312064243707,
  '2021-06': 100.0}})

I want to make a heatmap plot of it by line, but ignoring the max values, since they are much higher than the other values.

I also want to give the nans a light color, like white, but I got this part got right.

This is what I got so far:

df.style.background_gradient(cmap ='RdYlGn', axis=1)\
                .highlight_null(null_color='white')

Which produces this table:

enter image description here

How can I apply the gradient ignoring the values equal to 100?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57

1 Answers1

0

If I understand correctly, here is a suggestion (highly inspired by @quant's answer here) :

import pandas as pd
import numpy as np

df = pd.DataFrame({'2021-04': {'2021-04': 100.0, '2021-05': float("nan"), '2021-06': float("nan")},
 '2021-05': {'2021-04': 9.599326432568967, '2021-05': 100.0, '2021-06': float("nan")},
 '2021-06': {'2021-04': 7.952995602884856,
  '2021-05': 5.549312064243707,
  '2021-06': 100.0}})

def highlight_max(data, color='white'):
    attr = f'background-color: {color}'
    if data.ndim == 1:
        is_max = data == data.max()
        return [attr if v else '' for v in is_max]
    else:
        is_max = data == data.max().max()
        return pd.DataFrame(np.where(is_max, attr, ''),
                            index=data.index, columns=data.columns)
    
out = (df.style.background_gradient(cmap ='RdYlGn', axis=1)
      .highlight_null(null_color='white')
      .applymap(lambda x: 'color: white' if pd.isnull(x) else 'color: black')
      .apply(highlight_max, axis=None)
     )

>>> print(out)

enter image description here

Timeless
  • 22,580
  • 4
  • 12
  • 30
  • Thank you very much for you answered, but I don't think that it actually answers the question. As you can see, the values other than 100 are totally red. So the gradient is considering the 100 as the highest value, and it sould be the 9.599 – Sergio Polimante Aug 30 '22 at 18:38