sta*_*010 4 html python pandas
我在Jupyter/IPython笔记本中有一个Pandas数据框.作为Jupyter内部的HTML表格的数据框样式非常好.标题行具有粗体样式,字体很好,表格边框很薄.
df.to_html('myfile.html')
Run Code Online (Sandbox Code Playgroud)
但是生成的HTML文件的表样式并不好.
该文件中的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>
Run Code Online (Sandbox Code Playgroud)
如何直接从我的Python/Pandas代码修改此导出表的样式?
sta*_*010 15
我编写了一个Python函数,它基本上将HTML添加<style>到数据框的HTML表示中,以便生成的HTML表看起来不错.
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
result += df.to_html(classes='wide', escape=False)
result += '''
</body>
</html>
'''
with open(filename, 'w') as f:
f.write(result)
Run Code Online (Sandbox Code Playgroud)
当您将其写入.html文件时,这是生成的HTML.注意数据帧的to_html()输出如何适合中间.
下面是我的函数的一些示例用法.我首先加载一个数据集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()
Run Code Online (Sandbox Code Playgroud)
在Jupyter/IPython Notebook中,该表看起来非常不错:
我可以将数据帧写出一个HTML文件,其常规to_html()功能如下:
data1.to_html('iris.html')
Run Code Online (Sandbox Code Playgroud)
但是,结果看起来并不好,如下所示.边框很厚,字体不舒服,因为这只是<table> ... </table>没有造型.
为了使数据框在HTML中看起来更好,我使用了上面的函数.
write_to_html_file(data1, 'Iris data set', 'iris2.html')
Run Code Online (Sandbox Code Playgroud)
这个表现在看起来好多了因为我应用了样式.我还添加了行突出显示.
| 归档时间: |
|
| 查看次数: |
7066 次 |
| 最近记录: |