看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
pandas.DataFrame.to_html() 是 Pandas 库中用于将 DataFrame 对象转换为 HTML 表格格式的方法。该方法可以将数据以 HTML 表格的形式导出,便于在网页中展示、报告中嵌入或与其他 Web 应用程序集成。
DataFrame.to_html(
buf=None,
*,
columns=None,
col_space=None,
header=True,
index=True,
na_rep='NaN',
formatters=None,
float_format=None,
sparsify=None,
index_names=True,
justify=None,
max_rows=None,
max_cols=None,
show_dimensions=False,
decimal='.',
bold_rows=True,
classes=None,
escape=True,
notebook=False,
border=None,
table_id=None,
render_links=False,
encoding=None
)
以下是 DataFrame.to_html 方法的各个参数及其意义:
buf
str、pathlib.Path、file-like object、NoneNoneNone,则返回生成的 HTML 字符串;如果指定为文件路径或文件对象,则将 HTML 写入该位置。columns
list-like 或 NoneNoneNone,则包含所有列。col_space
int 或 dict,可选Noneheader
bool 或 list-like,可选TrueTrue(包含)、False(不包含)或指定特定的行作为表头。index
bool,可选TrueTrue 表示包含,False 表示不包含。na_rep
str'NaN'NaN)的表示方式。formatters
dict 或 list,可选Nonefloat_format
str 或 callable,可选None'%.2f' 表示保留两位小数。sparsify
bool 或 None,可选NoneTrue 表示在重复的索引标签处显示空白,False 表示重复显示。index_names
bool,可选Truejustify
{'left', 'right', 'center', 'justify', None}None'left'、'right'、'center'、'justify' 或 None(自动选择)。max_rows
int 或 None,可选Nonemax_cols
int 或 None,可选Noneshow_dimensions
bool,可选Falsedecimal
str'.'bold_rows
boolTrueclasses
str 或 list-like,可选Noneescape
boolTrueFalse,则允许 HTML 标签直接渲染。notebook
boolFalseTrue,则生成适用于 Jupyter Notebook 的 HTML 表格。border
int 或 None,可选NoneNone 表示不添加边框。table_id
str,可选Noneid 属性。render_links
boolFalseTrue,则将符合 URL 格式的字符串转换为可点击的链接。encoding
str,可选None'utf-8'。str 或 Nonebuf 为 None,则返回一个包含 HTML 表格的字符串。buf(文件路径或文件对象),则将 HTML 表格写入指定的位置,返回 None。DataFrame.to_html() 常用于以下场景:
import pandas as pd
# 构造示例数据
data = {
'姓名': ['艾丽丝', '鲍勃', '查理'],
'年龄': [30, 25, 35],
'城市': ['纽约', '洛杉矶', '芝加哥']
}
df = pd.DataFrame(data)
# 将 DataFrame 转换为 HTML 字符串
html_str = df.to_html()
print(html_str)
输出
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>姓名</th>
<th>年龄</th>
<th>城市</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>艾丽丝</td>
<td>30</td>
<td>纽约</td>
</tr>
<tr>
<th>1</th>
<td>鲍勃</td>
<td>25</td>
<td>洛杉矶</td>
</tr>
<tr>
<th>2</th>
<td>查理</td>
<td>35</td>
<td>芝加哥</td>
</tr>
</tbody>
</table>
import pandas as pd
# 构造示例数据
data = {
'姓名': ['艾丽丝', '鲍勃', '查理'],
'年龄': [30, 25, 35],
'城市': ['纽约', '洛杉矶', '芝加哥']
}
df = pd.DataFrame(data)
# 将 DataFrame 写入 HTML 文件
df.to_html('data.html', index=False, classes='table table-striped', border=0)
# 读取并打印 HTML 文件内容
with open('data.html', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
输出
<table class="table table-striped" border="0">
<thead>
<tr style="text-align: right;">
<th>姓名</th>
<th>年龄</th>
<th>城市</th>
</tr>
</thead>
<tbody>
<tr>
<td>艾丽丝</td>
<td>30</td>
<td>纽约</td>
</tr>
<tr>
<td>鲍勃</td>
<td>25</td>
<td>洛杉矶</td>
</tr>
<tr>
<td>查理</td>
<td>35</td>
<td>芝加哥</td>
</tr>
</tbody>
</table>
import pandas as pd
# 构造示例数据
data = {
'姓名': ['艾丽丝', '鲍勃', '查理'],
'年龄': [30, 25, 35],
'城市': ['纽约', '洛杉矶', '芝加哥'],
'职业': ['工程师', '设计师', '医生']
}
df = pd.DataFrame(data)
# 将指定列转换为 HTML,并不包含索引
html_str = df.to_html(columns=['姓名', '城市'], index=False)
print(html_str)
输出
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th>姓名</th>
<th>城市</th>
</tr>
</thead>
<tbody>
<tr>
<td>艾丽丝</td>
<td>纽约</td>
</tr>
<tr>
<td>鲍勃</td>
<td>洛杉矶</td>
</tr>
<tr>
<td>查理</td>
<td>芝加哥</td>
</tr>
</tbody>
</table>
import pandas as pd
# 构造示例数据
data = {
'姓名': ['艾丽丝', '鲍勃', '查理'],
'成绩': [95.123456, 88.987654, 92.456789]
}
df = pd.DataFrame(data)
# 定义格式化函数
formatters = {
'成绩': lambda x: f"{x:.2f}"
}
# 将 DataFrame 转换为 HTML,应用格式化函数
html_str = df.to_html(formatters=formatters, float_format="%.2f")
print(html_str)
输出
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>姓名</th>
<th>成绩</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>艾丽丝</td>
<td>95.12</td>
</tr>
<tr>
<th>1</th>
<td>鲍勃</td>
<td>88.99</td>
</tr>
<tr>
<th>2</th>
<td>查理</td>
<td>92.46</td>
</tr>
</tbody>
</table>
import pandas as pd
# 构造包含非 ASCII 字符的示例数据
data = {
'姓名': ['艾丽丝', '鲍勃', '查理'],
'年龄': [30, 25, 35],
'城市': ['纽约', '洛杉矶', '芝加哥']
}
df = pd.DataFrame(data)
# 将 DataFrame 转换为 HTML 字符串,不强制 ASCII 并使用缩进
html_str = df.to_html(force_ascii=False, indent=2)
print(html_str)
输出
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>姓名</th>
<th>年龄</th>
<th>城市</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>艾丽丝</td>
<td>30</td>
<td>纽约</td>
</tr>
<tr>
<th>1</th>
<td>鲍勃</td>
<td>25</td>
<td>洛杉矶</td>
</tr>
<tr>
<th>2</th>
<td>查理</td>
<td>35</td>
<td>芝加哥</td>
</tr>
</tbody>
</table>
import pandas as pd
# 构造示例数据
data = {
'姓名': ['艾丽丝', '鲍勃', '查理'],
'年龄': [30, 25, 35],
'城市': ['纽约', '洛杉矶', '芝加哥']
}
df = pd.DataFrame(data)
# 将 DataFrame 转换为 HTML,添加 CSS 类和表格 ID
html_str = df.to_html(classes='table table-bordered', table_id='my_table')
print(html_str)
输出
<table border="1" class="dataframe table table-bordered" id="my_table">
<thead>
<tr style="text-align: right;">
<th></th>
<th>姓名</th>
<th>年龄</th>
<th>城市</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>艾丽丝</td>
<td>30</td>
<td>纽约</td>
</tr>
<tr>
<th>1</th>
<td>鲍勃</td>
<td>25</td>
<td>洛杉矶</td>
</tr>
<tr>
<th>2</th>
<td>查理</td>
<td>35</td>
<td>芝加哥</td>
</tr>
</tbody>
</table>
import pandas as pd
# 构造示例数据
data = {
'姓名': ['艾丽丝', '鲍勃', '查理'],
'个人主页': [
'<a href="https://example.com/alice">Alice\'s Page</a>',
'<a href="https://example.com/bob">Bob\'s Page</a>',
'<a href="https://example.com/charlie">Charlie\'s Page</a>'
]
}
df = pd.DataFrame(data)
# 将 DataFrame 转换为 HTML,渲染链接
html_str = df.to_html(escape=False, render_links=True)
print(html_str)
输出
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>姓名</th>
<th>个人主页</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>艾丽丝</td>
<td><a href="https://example.com/alice">Alice's Page</a></td>
</tr>
<tr>
<th>1</th>
<td>鲍勃</td>
<td><a href="https://example.com/bob">Bob's Page</a></td>
</tr>
<tr>
<th>2</th>
<td>查理</td>
<td><a href="https://example.com/charlie">Charlie's Page</a></td>
</tr>
</tbody>
</table>
DataFrame.to_html() 是一个强大的方法,用于将 Pandas 的 DataFrame 对象导出为 HTML 表格格式。通过灵活配置参数,可以控制输出的 HTML 表格的样式、内容和结构,满足不同的展示和集成需求。无论是用于网页展示、报告生成还是数据集成,掌握 to_html() 的使用方法都能显著提升数据的可视化和共享效率。
更新时间:2024-10-10 09:13:59 标签:pandas python html