pandas 数据框的颜色行并转换为 HTML 表

luc*_*esg 9 html python pandas

我正在尝试使用烧瓶显示熊猫数据框。我成功地这样做了,直到我决定为数据框的一些行着色。特别是当我应用to_html()熊猫的方法时我失败了。

以下代码获取一个表,其中一些行以黄色显示:

import pandas as pd
import numpy as np

np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})

df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
               axis=1)
df.iloc[0, 2] = np.nan

def highlight_greaterthan(s,threshold,column):
    is_max = pd.Series(data=False, index=s.index)
    is_max[column] = s.loc[column] >= threshold
    return ['background-color: yellow' if is_max.any() else '' for v in is_max]


df = df.style.apply(highlight_greaterthan,threshold=1.0,column=['C','B'], axis=1)
display(df)
Run Code Online (Sandbox Code Playgroud)

接下来,当我运行to_html()它时,一切都崩溃了。

df_html = df.to_html

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-28-4d0cc094240b> in <module>()
----> 1 df_html = df.to_html

AttributeError: 'Styler' object has no attribute 'to_html'
Run Code Online (Sandbox Code Playgroud)

关于如何保留行颜色的任何想法?谢谢!

Edg*_*gón 8

As the error message indicates, you are trying to use the DataFrame.to_html() method on a Styler object, since df.style.apply returns a Styler object and not a DataFrame.

The docs say you can use the render() method to render the HTML.

Something like this:

style1 = df.style.apply(highlight_greaterthan,threshold=1.0,column=['C','B'], axis=1)
df_html = style1.render()
Run Code Online (Sandbox Code Playgroud)

The output of style1.render() would be:

style1 = df.style.apply(highlight_greaterthan,threshold=1.0,column=['C','B'], axis=1)
df_html = style1.render()
Run Code Online (Sandbox Code Playgroud)