Reputation: 189
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:
How can I apply the gradient ignoring the values equal to 100?
Upvotes: 2
Views: 310
Reputation: 1234
You could use:
df.replace(100, np.nan).style.background_gradient(cmap ='RdYlGn', axis=1)\
.highlight_null(color='white')
If the "100" values are of no use.
Upvotes: 0
Reputation: 37787
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)
Upvotes: 0