有没有一种快速的方法将 pandas DataFrame 转换为漂亮的 HTML 表格?

16

问题: df.to_html()的输出结果只是一个普通的html表格,看起来并不好看:

丑陋的表格

与此同时,在Jupyter Notebook中展示dataframes的可视化效果更好,但如果有一种简单的方法可以复制这种效果,我还没有发现。

漂亮的表格

我知道可以通过修改df.style属性生成更美观的表格,但在我开始学习CSS之前,是否有人已经写了相应的函数可以实现这个功能呢?


2
这里有一些你可能会用到的信息:https://rstudio.github.io/DT/010-style.html - cosinepenguin
@cosinepenguin 我没有在那里看到有关Pandas的任何信息... - juanpa.arrivillaga
自从pandas 0.17.1版本以来,已经添加了许多样式选项。请查看文档 - juanpa.arrivillaga
5个回答

14

考虑我的数据框 df

df = pd.DataFrame(np.arange(9).reshape(3, 3), list('ABC'), list('XYZ'))

df

   X  Y  Z
A  0  1  2
B  3  4  5
C  6  7  8

我从我的Jupyter笔记本上抄袭了这个样式

my_style = """background-color: rgba(0, 0, 0, 0);
border-bottom-color: rgb(0, 0, 0);
border-bottom-style: none;
border-bottom-width: 0px;
border-collapse: collapse;
border-image-outset: 0px;
border-image-repeat: stretch;
border-image-slice: 100%;
border-image-source: none;
border-image-width: 1;
border-left-color: rgb(0, 0, 0);
border-left-style: none;
border-left-width: 0px;
border-right-color: rgb(0, 0, 0);
border-right-style: none;
border-right-width: 0px;
border-top-color: rgb(0, 0, 0);
border-top-style: none;
border-top-width: 0px;
box-sizing: border-box;
color: rgb(0, 0, 0);
display: table;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 12px;
height: 1675px;
line-height: 20px;
margin-left: 0px;
margin-right: 0px;
margin-top: 12px;
table-layout: fixed;
text-size-adjust: 100%;
width: 700px;
-webkit-border-horizontal-spacing: 0px;
-webkit-border-vertical-spacing: 0px;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"""

这段内容来自我的帖子

def HTML_with_style(df, style=None, random_id=None):
    from IPython.display import HTML
    import numpy as np
    import re

    df_html = df.to_html()

    if random_id is None:
        random_id = 'id%d' % np.random.choice(np.arange(1000000))

    if style is None:
        style = """
        <style>
            table#{random_id} {{color: blue}}
        </style>
        """.format(random_id=random_id)
    else:
        new_style = []
        s = re.sub(r'</?style>', '', style).strip()
        for line in s.split('\n'):
                line = line.strip()
                if not re.match(r'^table', line):
                    line = re.sub(r'^', 'table ', line)
                new_style.append(line)
        new_style = ['<style>'] + new_style + ['</style>']

        style = re.sub(r'table(#\S+)?', 'table#%s' % random_id, '\n'.join(new_style))

    df_html = re.sub(r'<table', r'<table id=%s ' % random_id, df_html)

    return HTML(style + df_html)

然后我实现它。

HTML_with_style(df, '<style>table {{{}}}</style>'.format(my_style))

输入图片说明

你可以修改代码以转储html。

def HTML_with_style(df, style=None, random_id=None):
    import numpy as np
    import re

    df_html = df.to_html()

    if random_id is None:
        random_id = 'id%d' % np.random.choice(np.arange(1000000))

    if style is None:
        style = """
        <style>
            table#{random_id} {{color: blue}}
        </style>
        """.format(random_id=random_id)
    else:
        new_style = []
        s = re.sub(r'</?style>', '', style).strip()
        for line in s.split('\n'):
                line = line.strip()
                if not re.match(r'^table', line):
                    line = re.sub(r'^', 'table ', line)
                new_style.append(line)
        new_style = ['<style>'] + new_style + ['</style>']

        style = re.sub(r'table(#\S+)?', 'table#%s' % random_id, '\n'.join(new_style))

    df_html = re.sub(r'<table', r'<table id=%s ' % random_id, df_html)

    return style + df_html

现在

HTML_with_style(df, '<style>table {{{}}}</style>'.format(my_style))

'<style>\ntable#id850184 {background-color: rgba(0, 0, 0, 0);\ntable#id850184 border-bottom-color: rgb(0, 0, 0);\ntable#id850184 border-bottom-style: none;\ntable#id850184 border-bottom-width: 0px;\ntable#id850184 border-collapse: collapse;\ntable#id850184 border-image-outset: 0px;\ntable#id850184 border-image-repeat: stretch;\ntable#id850184 border-image-slice: 100%;\ntable#id850184 border-image-source: none;\ntable#id850184 border-image-width: 1;\ntable#id850184 border-left-color: rgb(0, 0, 0);\ntable#id850184 border-left-style: none;\ntable#id850184 border-left-width: 0px;\ntable#id850184 border-right-color: rgb(0, 0, 0);\ntable#id850184 border-right-style: none;\ntable#id850184 border-right-width: 0px;\ntable#id850184 border-top-color: rgb(0, 0, 0);\ntable#id850184 border-top-style: none;\ntable#id850184 border-top-width: 0px;\ntable#id850184 box-sizing: border-box;\ntable#id850184 color: rgb(0, 0, 0);\ntable#id850184 display: table#id850184;\ntable#id850184 font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\ntable#id850184 font-size: 12px;\ntable#id850184 height: 1675px;\ntable#id850184 line-height: 20px;\ntable#id850184 margin-left: 0px;\ntable#id850184 margin-right: 0px;\ntable#id850184 margin-top: 12px;\ntable#id850184-layout: fixed;\ntable#id850184 text-size-adjust: 100%;\ntable#id850184 width: 700px;\ntable#id850184 -webkit-border-horizontal-spacing: 0px;\ntable#id850184 -webkit-border-vertical-spacing: 0px;\ntable#id850184 -webkit-tap-highlight-color: rgba(0, 0, 0, 0);}\n</style><table id=id850184  border="1" class="dataframe">\n  <thead>\n    <tr style="text-align: right;">\n      <th></th>\n      <th>X</th>\n      <th>Y</th>\n      <th>Z</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>A</th>\n      <td>0</td>\n      <td>1</td>\n      <td>2</td>\n    </tr>\n    <tr>\n      <th>B</th>\n      <td>3</td>\n      <td>4</td>\n      <td>5</td>\n    </tr>\n    <tr>\n      <th>C</th>\n      <td>6</td>\n      <td>7</td>\n      <td>8</td>\n    </tr>\n  </tbody>\n</table>'

13
经过一些研究,我发现最漂亮和最简单的解决方案是https://pypi.org/project/pretty-html-table/
import pandas as pd
from pretty_html_table import build_table
df = pd.DataFrame(np.arange(9).reshape(3, 3), list('ABC'), list('XYZ'))
html_table_blue_light = build_table(df, 'blue_light')
print(html_table_blue_light)
with open('styled_table.html', 'w') as f:
    f.write(html_table_blue_light)

你知道怎么在HTML表格中减小字体大小吗?为这个解决方案点赞。 - The Great
感谢您的点赞。您可以传递 build_table(df, 'blue_light', font_size='25px')。请参见 https://www.w3schools.com/css/css_font_size.asp 以获取更多在 html 中声明 font-size 的方法。 - DaveR

2
您还可以在笔记本的顶部添加以下原始NBConvert单元格:
<link rel="stylesheet" href="https://cdn.jupyter.org/notebook/5.1.0/style/style.min.css">

NBConvert 似乎无法将这些样式添加到导出的 HTML 中。上面的行将显式地添加它们。 源代码

2

<link rel="stylesheet" href="https://cdn.jupyter.org/notebook/5.1.0/style/style.min.css">

你需要将class="rendered_html"添加到<body>,否则它将无法正常工作。


0
from pretty_html_table import build_table
df = pd.read_excel('df.xlsx')
html_table_blue_light = build_table(df, 'blue_light')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接