我想在熊猫数据框的多个子部分中应用颜色渐变(绿色到黄色到红色:基于值)。在每个小节中,值将介于 0 和 1 之间。
到目前为止,我所拥有的是:
def applyMetricGradient(df, idx_pairs, low=0, high=0):
def background_gradient(s, m, M, cmap='RdYlGn', 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]
for eachPair in idx_pairs:
start = eachPair[0]
end = eachPair[1]
display(df.loc[df.index[start:end]]['Values'].values.max().max())
df = df.style.apply(background_gradient,
cmap='RdYlGn',
m=df.loc[df.index[start:end]]['Values'].values.min().min(),
M=df.loc[df.index[start:end]]['Values'].values.max().max(),
low=0,
high=0.2,
subset = df.index[start:end], axis=0)
display(df)
applyMetricGradient(corrStat.set_index('Metrics'), [(0,3), (8,13)])
我收到此错误:
KeyError: "None of [Index(['a', 'b', 'c'], dtype='object', name='Metrics')] are in the [columns]"
编辑
我能够通过使用 pd.IndexSlice[] 将渐变放在一个子集上,
def applyMetricGradient(df, idx_pairs, low=0, high=0):
def background_gradient(s, m, M, cmap='RdYlGn', 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]
for eachPair in idx_pairs:
start = eachPair[0]
end = eachPair[1]
display(df.loc[df.index[start:end]]['Values'].values.max().max())
df = df.style.apply(background_gradient,
cmap='RdYlGn',
m=df.loc[df.index[start:end]]['Values'].values.min().min(),
M=df.loc[df.index[start:end]]['Values'].values.max().max(),
low=0,
high=0.2,
subset = pd.IndexSlice[df.index[start:end], 'Values'], axis=1)
display(df)
applyMetricGradient(corrStat.set_index('Metrics'), [(0,3), (8,13)])
但是对于下一个子集,我得到
AttributeError: 'Styler' object has no attribute 'loc'
有什么解决方法吗?