python3 + Pandas 样式 + 更改备用行颜色

Vin*_* HC 5 python python-2.7 python-3.x pandas sklearn-pandas

嗨,我正在使用 Pandas 并显示一张表格。我有一个功能可以应用交替行颜色以使其清晰易读。使用下面的代码我在邮件中发送表格并且它有效。

我的代码:

count = 1000
df = pandas.DataFrame.from_dict(result)
df["Total"] = df.T.sum()

html = """<!DOCTYPE html>
<html>
    <body>
    <h3> %i</h3>
    {table_content}
    </body>
</html>
""" % count


# Create message container - the correct MIME type is
# multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = " Report"
msg['From'] = sender
msg['To'] = recipients


part2 = MIMEText(html.df(
    table_content=df.to_html(na_rep="0")), 'html')

msg.attach(part2)
Run Code Online (Sandbox Code Playgroud)

omd*_*mdv 9

您可以使用 CSS,即tr:nth-childdf.to_html(classes)

根据您的情况采用:

from IPython.display import display, HTML
from sklearn.datasets import load_iris
import pandas as pd
import numpy as np

iris = load_iris()
df = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                     columns= iris['feature_names'] + ['target'])
HTML('''
        <style>
            .df tbody tr:nth-child(even) { background-color: lightblue; }
        </style>
        ''' + df.to_html(classes="df"))
Run Code Online (Sandbox Code Playgroud)

Jupyter 笔记本的屏幕截图

更新:扩展到特定示例

我稍微重新安排了代码以允许添加 css,因为它{}.format. 您可以将变量添加到 html_variables 字典中并用于%()s将它们嵌入到 html 中。如果您的 html 变得太复杂,我建议您考虑使用一些模板引擎以使其更加健壮。否则下面的代码应该是不言自明的。

html_template = '''<!DOCTYPE html>
<html>
    <head>
    <style>.df tbody tr:nth-child(even) {background-color: lightblue;}</style>
    </head>
    <body>
    <h3>%(other_var)s</h3>
    %(table_content)s
    </body>
</html>
'''

html_vars = {'other_var':'IRIS Dataset','table_content':df.to_html(classes="df")}

html = html_template % html_vars

# Create message container - the correct MIME type is
# multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Report"
msg['From'] = sender
msg['To'] = recipient

part2 = MIMEText(html, 'html')
msg.attach(part2)
Run Code Online (Sandbox Code Playgroud)


小智 6

老问题,但我在 pandas 框架中找到了一个解决方案,供将来使用:

    def rower(data):
        s = data.index % 2 != 0
        s = pd.concat([pd.Series(s)] * data.shape[1], axis=1) #6 or the n of cols u have
        z = pd.DataFrame(np.where(s, 'background-color:#f2f2f2', ''),
                     index=data.index, columns=data.columns)
        return z

df.style.apply(rower, axis=None)
Run Code Online (Sandbox Code Playgroud)