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. (我还添加了行突出显示。)