我正在尝试将Python Pandas Data Frame
中定义的另存为HTML
页面。另外,我想将此表另存为HTML
表功能,以便按任何列的值进行过滤。您能否提供可能的解决方案?最后,应将该表保存为HTML
页。我想将此代码合并到我的Python
代码中。谢谢
您可以使用pandas.DataFrame.to_html()
。
pandas.DataFrame.to_html()
这会将以下html保存到>>> import numpy as np
>>> from pandas import *
>>> df = DataFrame({'foo1' : np.random.randn(2),
'foo2' : np.random.randn(2)})
>>> df.to_html('filename.html')
。
filename.html
。to_html()也可用于创建html字符串
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>foo1</th>
<th>foo2</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>-0.223430</td>
<td>-0.904465</td>
</tr>
<tr>
<th>1</th>
<td>0.317316</td>
<td>1.321537</td>
</tr>
</tbody>
</table>
import io
import pandas as pd
from numpy.random import randn
df = pd.DataFrame(
randn(5, 4),
index = 'A B C D E'.split(),
columns = 'W X Y Z'.split()
)
str_io = io.StringIO()
df.to_html(buf=str_io, classes='table table-striped')
html_str = str_io.getvalue()
print(html_str)