Python Pandas数据框另存为HTML页面

问题描述 投票:20回答:2

我正在尝试将Python Pandas Data Frame中定义的另存为HTML页面。另外,我想将此表另存为HTML表功能,以便按任何列的值进行过滤。您能否提供可能的解决方案?最后,应将该表保存为HTML页。我想将此代码合并到我的Python代码中。谢谢

python html pandas
2个回答
40
投票

您可以使用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

5
投票

。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)
© www.soinside.com 2019 - 2024. All rights reserved.