【问题标题】:python3 + Pandas styles + Change alternate row colorpython3 + Pandas 样式 + 更改备用行颜色
【发布时间】:2017-07-23 10:08:32
【问题描述】:

您好,我正在使用 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)

【问题讨论】:

    标签: python python-2.7 python-3.x pandas sklearn-pandas


    【解决方案1】:

    您可以使用 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"))
    

    更新:扩展至特定示例

    我稍微重新安排了代码以允许添加 css,因为它与 .format 使用的 {} 冲突。您可以将变量添加到 html_variables dict 并使用 %()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)
    

    【讨论】:

    • 嗨,托里诺斯,谢谢!如果我将此 html 内容放在显示中 (HTML(....))) 它只打印对象而不是实际的表格。在我的情况下,我将 html 模板分配给名为 html 的变量,那么在我的情况下如何实现这一点。
    • 试试上面的例子。我在准确复制您的案例时遇到问题 - 不想设置 smtp 服务器来尝试发送消息,我正在使用 Jupyter 笔记本检查 html 是否正确呈现。上面的例子对我有用。
    【解决方案2】:

    老问题,但我在 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)
    

    【讨论】:

      猜你喜欢
      • 2016-10-29
      • 1970-01-01
      • 1970-01-01
      • 2012-12-23
      • 2010-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多