使用 python 将 pandas dataframe 保存为 html-ag捕鱼王app官网

使用 python 将 pandas dataframe 保存为 html

作者:迹忆客 最近更新:2024/04/21 浏览次数:

有时我们将 dataframe 渲染为 html 表格以在网页中表示它。如果我们想在 html 中显示同一个表格,我们不需要在 html 中编写它的代码来重新制作那个表格。

我们可以使用内置的方法或在 python 中手动编写代码来将 pandas dataframe 转换为 html 表格,这将在本文中讨论。


使用 to_html() 方法将 pandas dataframe 保存为 html 文件

在下面的代码中,我们有学生的数据。我们使用 pandas 库中提供的方法 to_html() 将 pandas dataframe 转换为 html。

我们将使用我们的 dataframe 对象调用此方法,并传递表示表格的新 html 文件的名称。如果我们只传递 html 文件的名称,它将在当前目录中创建。

我们还可以提供路径以及 html 文件的名称,以将其保存在其他位置。此方法会将整个 dataframe 转换为

元素,并且列将包裹在 元素中。

dataframe 的每一行都将被包裹在 html 的

元素中。此方法将返回 dataframe 的 html 格式。

示例代码:

# python 3.x
import pandas as pd
df = pd.read_csv("student.csv")
display(df)
df.to_html("student.html")

输出:

输出将在 student.html 文件中。

html - 代码:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th>th>
      <th>st_nameth>
      <th>departmentth>
      <th>marksth>
    tr>
  thead>
  <tbody>
    <tr>
      <th>0th>
      <td>jhontd>
      <td>cstd>
      <td>60td>
    tr>
    <tr>
      <th>1th>
      <td>aliatd>
      <td>eetd>
      <td>80td>
    tr>
    <tr>
      <th>2th>
      <td>samtd>
      <td>eetd>
      <td>90td>
    tr>
    <tr>
      <th>3th>
      <td>smithtd>
      <td>cstd>
      <td>88td>
    tr>
  tbody>
table>

手动将 pandas dataframe 转换为 html

将 pandas dataframe 保存为 html 的另一种方法是从头开始编写代码以进行手动转换。

首先,我们在下面的代码中以 w 模式打开了一个文件 student.html。如果文件不存在,此模式将创建一个文件。

在这个文件中,我们的 html 代码将被保存。在这里,我们将整个表包裹在

中,然后我们遍历 dataframe 的列并将它们包裹在 中。

示例代码:

# python 3.x
import pandas as pd
df = pd.read_csv("student.csv")
display(df)
with open(r"student.html", "w ") as f:
    f.write("
中。

最后,我们对行进行了迭代并将它们包装在

") for header in df.columns.values: f.write("") for i in range(len(df)): f.write("") for col in df.columns: value = df.iloc[i][col] f.write("") f.write("") f.write("
" str(header) "
" str(value) "
")

输出:

html - 代码:

<table><th>st_nameth><th>departmentth><th>marksth><tr><td>jhontd><td>cstd><td>60td>tr><tr><td>aliatd><td>eetd><td>80td>tr><tr><td>samtd><td>eetd><td>90td>tr><tr><td>smithtd><td>cstd><td>88td>tr>table>

上一篇:

下一篇:填充 pandas dataframe 中的缺失值

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:python

pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 dataframe 中。

pandas 追加数据到 csv 中

发布时间:2024/04/24 浏览次数:352 分类:python

本教程演示了如何在追加模式下使用 to_csv()向现有的 csv 文件添加数据。

pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:python

本教程介绍了如何在 pandas 中使用 dataframe.merge()方法合并两个 dataframes。

pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:python

本教程介绍了如何使用 python 中的 loc 和 iloc 从 pandas dataframe 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便
网站地图