2

我想组合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.applypandas 的方法,但遇到了与上述类似的错误。

4

1 回答 1

3

我在这里找到了基于信息的解决方案:mode.com/example-gallery/python_dataframe_styling

您可以简单地将多个样式方法同时传递给同一个数据框,而不是尝试使用更多样式方法强制样式对象。请看下面:

# example data frame
df = pd.DataFrame(np.random.randn(15).reshape(5, 3))

# pass multiple style methods to same  data frame
styled_df = (df.style
             .background_gradient(subset=[0, 1], # background_gradient method
                                  low=0, high=0.5,
                                  cmap="YlGnBu")
             .bar(subset=[2], align='mid',       # bar method
                  color=['#d65f5f', '#5fba7d']))

# Export "styled_df" to html
html = styled_df.hide_index().render()
with open("html_c.html","w") as fp:
   fp.write(html)
于 2019-02-09T11:03:53.570 回答