【问题标题】:Can I add a header/title row above the column labels of a pandas dataframe and output it to HTML?我可以在 pandas 数据框的列标签上方添加标题/标题行并将其输出到 HTML 吗?
【发布时间】:2020-01-28 19:02:34
【问题描述】:

根据下面的示例,我将数据框输出到电子邮件正文。是否可以在列标签行上方添加标题或标题行?最好是一个单元格的行,数据帧的长度,包含一个字符串?

import pandas as pd
import numpy as np
from IPython.core.display import display, HTML

dates = pd.date_range('20130101',periods=3)
df = pd.DataFrame(np.random.randn(3,4),index=dates,columns=list('ABCD'))

styles = [{'props':[("font-family", "Calibri")]}, {
       'selector': 'th',
       'props': [
           ('background-color', 'yellow')]}]
s = df.style.set_table_styles(styles)

html = s.hide_index().render()
with open("html_c.html","w") as fp:
   fp.write(html)
#to display in a jupyter notebook
display(HTML(html))

当前输出:

期望的输出:

【问题讨论】:

    标签: python html pandas


    【解决方案1】:

    也许是这样的?

    import pandas as pd
    import numpy as np
    from IPython.core.display import display, HTML
    
    dates = pd.date_range('20130101',periods=3)
    
    ### >>> begin
    columns = list("ABCD")
    columns = list(zip(['HEADER'] * 4, columns))             
    #[('HEADER', 'A'), ('HEADER', 'B'), ('HEADER', 'C'), ('HEADER', 'D')]
    columns = pd.MultiIndex.from_tuples(columns, names=['first', 'second'])    
    ### >>> end
    
    df = pd.DataFrame(np.random.randn(3,4),index=dates,columns=columns) # <--- also here
    styles = [{'props':[("font-family", "Calibri")]}, {
           'selector': 'th',
           'props': [
               ('background-color', 'yellow'),
               ('text-align','center')] # for alignment
            }]
    s = df.style.set_table_styles(styles)
    
    html = s.hide_index().render()
    with open("html_c.html","w") as fp:
       fp.write(html)
    #to display in a jupyter notebook
    display(HTML(html))
    

    【讨论】:

    • 后续问题:它在 Jupyter 中看起来很完美,但是当我导出到电子邮件正文时,只有第一级索引有背景色,第二级没有背景色。我正在使用win32发送电子邮件:```#send email with html in body outlook = win32.Dispatch('outlook.application') mail = outlook.CreateItem(0) mail.To = #email address mail.Subject = “HTML 测试”mail.HTMLBody = html mail.Send() ```
    • 嗯,这有点棘手,因为它不再是 Pandas.Dataframe 方面的问题,您可能需要发布另一个问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 2019-10-12
    • 2015-01-18
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多