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

时间:2017-03-03 10:31:02

标签: 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)

2 个答案:

答案 0 :(得分:2)

您可以使用CSS,即df.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"))

组合使用

采纳你的情况:

{}

Screenshot from Jupyter notebook

更新:扩展为特定示例

我稍微重新安排了代码以允许添加css,因为它与.format使用的%()s冲突。您可以将变量添加到html_variables dict并使用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变得太复杂,我建议您使用一些模板引擎来使其更加健壮。否则,下面的代码应该是不言自明的。

awk -F"|" '{for(i=4;i<=NF;i++){printf("%s%s",$i,i==NF?"":"|")};print ""}'  Input_file

答案 1 :(得分:0)

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