pandas DataFrame样式就像Excel Graded色阶条件格式

时间:2018-06-06 10:27:30

标签: python pandas

使用Graded颜色格式时,我想在Excel中渲染DataFrame:

enter image description here

我无法通过Pandas(v0.23.0)样式得到类似的结果:

import pandas as pd
import numpy as np

shape = (3,3)

np.random.seed(0)
df=pd.DataFrame(np.random.uniform(0.,144, size=9).reshape(shape))
df.iloc[0,0] = np.nan
df.iloc[1,1] = 144
df.iloc[0,2] = 0
df[3] = 144

df.style.background_gradient(cmap='RdYlGn').highlight_null('white')

这就是我得到的:

enter image description here

有什么想法吗?

谢谢, 格雷格

修改

此解决方案有效:

import matplotlib.pyplot as plt
from matplotlib import colors

def background_gradient(s, m, M, cmap='PuBu', low=0, high=0):
    rng = M - m
    norm = colors.Normalize(m - (rng * low),
                            M + (rng * high))
    normed = norm(s.values)
    c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)]
    return ['background-color: %s' % color for color in c]

df.style.apply(background_gradient,
               cmap='RdYlGn',
               m=df.min().min(),
               M=144).highlight_null('white')

0 个答案:

没有答案