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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47704441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:52:16  来源:igfitidea点击:

Applying styling to Pandas dataframe saved to HTML file

pythonhtmlpandas

提问by stackoverflowuser2010

I have a Pandas dataframe inside of a Jupyter / IPython notebook. The dataframe's style as an HTML table inside of Jupyter is pretty nice. The header row has bold style, the font is nice, and the table borders are thin.

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

enter image description here

在此处输入图片说明

I then export the dataframe to an HTML file (following instructions hereand here):

然后我将数据框导出到 HTML 文件(按照此处此处的说明进行操作):

df.to_html('myfile.html')

But the resulting HTML file's table styling is not good.

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

enter image description here

在此处输入图片说明

The HTML in that file is plain:

该文件中的 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>

How do I modify the styling of this exported table directly from my Python / Pandas code?

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

回答by stackoverflowuser2010

I wrote a Python function that basically adds an HTML <style>to the dataframe's HTML representation so that the resulting HTML table looks nice.

我编写了一个 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)

Here's the resulting HTML when you write it to an .html file. Note how the dataframe's to_html()output fits into the middle.

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

enter image description here

在此处输入图片说明

Below is some example usage of my function. I first load up a dataset from sklearnto demonstrate.

下面是我的函数的一些示例用法。我首先加载一个数据集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()

In Jupyter / IPython Notebook, the table looks pretty nice:

在 Jupyter / IPython Notebook 中,表格看起来非常漂亮:

enter image description here

在此处输入图片说明

I can write out the dataframe to an HTML file with the usual to_html()function like this:

我可以使用如下常用to_html()函数将数据框写到 HTML 文件中:

data1.to_html('iris.html')

However, the result doesn't look good, as shown below. The border is thick and font is not pleasant because this is just a <table> ... </table>with no styling.

但是,结果看起来并不好,如下所示。边框很粗,字体也不舒服,因为这只是一个<table> ... </table>没有样式的。

enter image description here

在此处输入图片说明

To make the dataframe look better in HTML, I used my function above.

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

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

The table looks much nicer now because I applied styling. I also added row highlighting.

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

enter image description here

在此处输入图片说明