将样式应用于保存到HTML文件的Pandas数据框 [英] Applying styling to Pandas dataframe saved to HTML file

查看:83
本文介绍了将样式应用于保存到HTML文件的Pandas数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

df.to_html('myfile.html')

但是结果HTML文件的表样式不好.

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

该文件中的HTML是纯文本:

The HTML in that file is plain:

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

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

推荐答案

我编写了一个Python函数,该函数基本上将HTML <style>添加到数据框的HTML表示中,以使生成的HTML表看起来很漂亮.

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.

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()输出如何适合中间位置.

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.

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

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

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中,该表看起来非常漂亮:

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

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

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

data1.to_html('iris.html')

但是,结果看起来并不理想,如下所示.边框很粗,字体令人不愉快,因为这只是一个没有样式的<table> ... </table>.

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.

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

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

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.

这篇关于将样式应用于保存到HTML文件的Pandas数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆