python - 将样式应用于保存到 HTML 文件的 Pandas 数据框

标签 python html pandas

我在 Jupyter/IPython 笔记本中有一个 Pandas 数据框。作为 Jupyter 中的 HTML 表格的数据框样式非常好。标题行粗体,字体漂亮,表格边框细。

enter image description here

然后我将数据框导出到 HTML 文件(按照说明 herehere ):

df.to_html('myfile.html')

但是生成的 HTML 文件的表格样式并不好。

enter image description here

该文件中的 HTML 是纯文本:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Id</th>
      <th>Index</th>
      <th>Feature</th>
      <th>Timestamp</th>
      <th>Feature2</th>
    </tr>
  </thead>

如何直接从我的 Python/Pandas 代码修改此导出表格的样式?

最佳答案

我写了一个 Python 函数,基本上添加了一个 HTML <style>到数据框的 HTML 表示形式,以便生成的 HTML 表格看起来不错。

import pandas as pd

def write_to_html_file(df, title='', filename='out.html'):
    '''
    Write an entire dataframe to an HTML file with nice formatting.
    '''

    result = '''
<html>
<head>
<style>

    h2 {
        text-align: center;
        font-family: Helvetica, Arial, sans-serif;
    }
    table { 
        margin-left: auto;
        margin-right: auto;
    }
    table, th, td {
        border: 1px solid black;
        border-collapse: collapse;
    }
    th, td {
        padding: 5px;
        text-align: center;
        font-family: Helvetica, Arial, sans-serif;
        font-size: 90%;
    }
    table tbody tr:hover {
        background-color: #dddddd;
    }
    .wide {
        width: 90%; 
    }

</style>
</head>
<body>
    '''
    result += '<h2> %s </h2>\n' % title
    if type(df) == pd.io.formats.style.Styler:
        result += df.render()
    else:
        result += df.to_html(classes='wide', escape=False)
    result += '''
</body>
</html>
'''
    with open(filename, 'w') as f:
        f.write(result)

这是将其写入 .html 文件时生成的 HTML。注意数据框的 to_html()输出适合中间。

enter image description here

下面是我的函数的一些示例用法。我首先从 sklearn 加载数据集进行演示。

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris

iris = load_iris()
data1 = pd.DataFrame(data=np.c_[iris['data'], iris['target']],
                     columns=iris['feature_names'] + ['target'])
data1.head()

在 Jupyter/IPython Notebook 中,表格看起来很不错:

enter image description here

我可以使用通常的 to_html() 将数据框写入 HTML 文件像这样的功能:

data1.to_html('iris.html')

然而,结果看起来并不好,如下图。边框很粗,字体也不好看,因为这只是一个 <table> ... </table>没有样式。

enter image description here

为了使 dataframe 在 HTML 中看起来更好,我使用了上面的函数。

write_to_html_file(data1, 'Iris data set', 'iris2.html')

表格现在看起来好多了,因为我应用了样式。我还添加了行突出显示。

enter image description here

关于python - 将样式应用于保存到 HTML 文件的 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47704441/

相关文章:

python - 机械化可以完全替换为请求[python]

python - Airflow 任务信息 - 任务退出并返回代码 -9

python - 从 csv 数据框中选择一列

python - 如何在 Pandas 中找到数字列?

python 比 perl mySql 查询慢 5 倍

python - 对函数参数的隐藏引用导致大量内存使用?

python - 如何从 OpenCV 中的图像中删除空白?

javascript - 用图像填充 div(忽略比例)

javascript - jQuery 中触发错误按钮的 Click 事件?

javascript - html 的静音/取消静音图标