Python 将pd.DataFrame样式器对象的背景渐变颜色贴图居中

Python 将pd.DataFrame样式器对象的背景渐变颜色贴图居中,python,pandas,matplotlib,Python,Pandas,Matplotlib,不确定是否可以在pandas Styler对象的框架下利用matplotlib。例如: import pandas as pd import matplotlib.cm # retrieve red-yellow-green diverging color map cmap = matplotlib.cm.get_cmap('RdYlGn') # create sample pd.DataFrame ix = pd.date_range(start=pd.Timestamp(2020, 1,

不确定是否可以在pandas Styler对象的框架下利用matplotlib。例如:

import pandas as pd
import matplotlib.cm

# retrieve red-yellow-green diverging color map
cmap = matplotlib.cm.get_cmap('RdYlGn')

# create sample pd.DataFrame
ix = pd.date_range(start=pd.Timestamp(2020, 1, 1), periods=4)
df = pd.DataFrame(index=ix, columns=['D/D CHANGE'], data=[-1, 0, 2, 5])

df.style.background_gradient(cmap=cmap)


理想情况下,只有负值(正值)才会显示为红色(绿色)

似乎没有一个选项可以将自定义规范化传递到
背景梯度
(可能是在github上发布的功能请求)。但您可以使用自定义函数来获得所需的结果:

def background_with_norm(s):
    cmap = matplotlib.cm.get_cmap('RdYlGn')
    norm = matplotlib.colors.DivergingNorm(vmin=s.values.min(), vcenter=0, vmax=s.values.max())
    return ['background-color: {:s}'.format(matplotlib.colors.to_hex(c.flatten())) for c in cmap(norm(s.values))]

# create sample pd.DataFrame
ix = pd.date_range(start=pd.Timestamp(2020, 1, 1), periods=4)
df = pd.DataFrame(index=ix, columns=['D/D CHANGE'], data=[-1, 0, 2, 5])

df.style.apply(background_with_norm)

效果很好。我添加了一个条件来确保s.values.min()<0