Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

python - 将样式应用于保存到HTML文件的Pandas数据框(Applying styling to Pandas dataframe saved to HTML file)

I have a Pandas dataframe inside of a Jupyter / IPython notebook.

(我在Jupyter / IPython笔记本中有一个Pandas数据框。)

The dataframe's style as an HTML table inside of Jupyter is pretty nice.

(Jupyter内的HTML表格的数据框样式非常好。)

The header row has bold style, the font is nice, and the table borders are thin.

(标题行具有粗体样式,字体漂亮,表格边框很细。)

在此处输入图片说明

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

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

df.to_html('myfile.html')

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

(但是,结果HTML文件的表样式不好。)

在此处输入图片说明

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代码修改此导出表的样式?)

  ask by stackoverflowuser2010 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>
' % 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.

(这是将其写入.html文件时得到的HTML。)

Note how the dataframe's to_html() output fits into the middle.

(请注意,数据框的to_html()输出如何适合中间位置。)

在此处输入图片说明

Below is some example usage of my function.

(以下是我的函数的一些示例用法。)

I first load up a dataset from sklearn to 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中,该表看起来非常漂亮:)

在此处输入图片说明

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> 。)

在此处输入图片说明

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.

(我还添加了行突出显示。)

在此处输入图片说明


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...