使用 python 将 pandas dataframe 保存为 html
有时我们将 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 的
示例代码:
# 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 代码将被保存。在这里,我们将整个表包裹在
中。示例代码:
# 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>
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
pandas dataframe dataframe.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:python
-
dataframe.shift() 函数是将 dataframe 的索引按指定的周期数进行移位。
python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:python
-
python pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:python
-
pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 dataframe 中。
pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:python
-
本教程介绍了如何在 pandas 中使用 dataframe.merge()方法合并两个 dataframes。
pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:python
-
本教程介绍了如何使用 python 中的 loc 和 iloc 从 pandas dataframe 中过滤数据。
在 python 中将 pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:python
-
了解如何在 python 中将 pandas 系列日期时间转换为字符串