You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将多个pandas交叉表导出至带目录的单个HTML文件

导出带目录的Pandas交叉表到单个HTML文件

准备数据与交叉表

先创建目标DataFrame并生成对应的交叉表:

import pandas as pd
import numpy as np

ds = {'col1' : [1,1,2,3,4], 'col2' : [1,1,3,4,5], 'col3': [3,3,3,3,3]}
df = pd.DataFrame(data=ds)

# 生成两个标准化后的交叉表
x1 = pd.crosstab(df['col1'], df['col2'], normalize='index').sort_index()
x2 = pd.crosstab(df['col1'], df['col3'], normalize='index').sort_index()

构建带目录的HTML内容

通过手动拼接HTML片段,实现顶部目录+锚点跳转的效果:

1. 整理交叉表信息

将交叉表与对应列名存入列表,方便统一处理:

# 存储交叉表及其关联的列名
crosstabs = [
    ("col2", x1),
    ("col3", x2)
]

2. 生成目录与交叉表HTML

先构建带锚点链接的目录,再逐个转换交叉表为HTML表格并添加锚点标记:

# 初始化HTML内容
html_content = "<h2>目录</h2>\n<ol>\n"

# 生成目录项(带跳转锚点)
for idx, (name, _) in enumerate(crosstabs, 1):
    html_content += f"  <li><a href='#{name}'>{name}</a></li>\n"
html_content += "</ol>\n<hr>\n"

# 添加每个交叉表的HTML内容
for name, table in crosstabs:
    # 添加锚点和标题
    html_content += f"<h3 id='{name}'>{name}</h3>\n"
    # 将DataFrame转为带样式的HTML表格
    html_content += table.to_html(classes='table table-bordered', border=1)
    html_content += "<br>\n"

3. 保存HTML文件

将拼接好的内容写入本地文件:

# 写入HTML文件,指定编码避免中文乱码
with open('crosstabs_with_toc.html', 'w', encoding='utf-8') as f:
    f.write(html_content)

最终效果

生成的HTML文件顶部会显示有序目录,点击目录项可直接跳转到对应交叉表区域,交叉表保留原数据格式与结构。


内容的提问来源于stack exchange,提问作者Giampaolo Levorato

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 20:51:06