我想组合df.style
使用以下方法的熊猫对象 -df.style.background_gradient
并将df.style.bar
结果导出到 html。
当我有单独的对象时,我就成功了。这是一个示例数据框:
df = pd.DataFrame(np.random.randn(15).reshape(5, 3))
然后我可以将其传递给不同的样式方法:
# Use method "background_gradient"
styled_df_a = df.style.background_gradient(subset=[0, 1],
low=0, high=0.5,
cmap="YlGnBu")
# Use method "bar"
styled_df_b = df.style.bar(subset=[2], align='mid',
color=['#d65f5f', '#5fba7d'])
我随后将每个样式表导出到 html:
# Export styled table a to html
html = styled_df_a.render()
with open("df_a.html","w") as fp:
fp.write(html)
# Export styled table b to html
html = styled_df_b.render()
with open("df_b.html","w") as fp:
fp.write(html)
因此,我有 2 个 html 呈现的样式表。但是,我想将这 2 种方法组合成 1 个 html 样式表,以便第 1-2 列具有background_gradient
样式,第 3 列具有bar
样式。
我试过这个:
styled_df_c = styled_df_a.style.bar(subset=[2], align='mid',
color=['#d65f5f', '#5fba7d'])
由于以下错误,这不起作用:
AttributeError: 'Styler' object has no attribute 'style'
有没有办法通过其他方式做到这一点?我确实尝试过使用style.apply
pandas 的方法,但遇到了与上述类似的错误。