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

如何在Pandas中创建指定样式的多级表头表格?

Pandas实现指定样式的多级表头表格

核心思路

要实现你需要的多级表头+多级行索引表格,关键是构建多级列索引(MultiIndex)和多级行索引(MultiIndex),再将你的数据集对应填充到结构中。

完整实现代码

import pandas as pd
import numpy as np

# 1. 构建多级行索引
row_tuples = [
    ("Education-only", ""),
    ("Medication Management", "ASCVD"),
    ("Medication Management", "DM"),
    ("Medication Management", "LDL>190"),
    ("Medication Management", "Primary Prevention")
]
row_index = pd.MultiIndex.from_tuples(row_tuples, names=["", ""])

# 2. 构建多级列索引
col_tuples = [
    ("6 Months", "LDL<100"),
    ("6 Months", "LDL<70"),
    ("6 Months", "LDL>50% Reduction"),
    ("1 Year", "LDL<100"),
    ("1 Year", "LDL<70"),
    ("1 Year", "LDL>50% Reduction")
]
col_index = pd.MultiIndex.from_tuples(col_tuples, names=["", ""])

# 3. 生成示例数据(替换成你自己的数据集即可)
# 若已有数据集,需将数据整理为5行6列的二维数组形式
data = np.random.randint(0, 100, size=(5, 6))

# 4. 创建DataFrame
df = pd.DataFrame(data, index=row_index, columns=col_index)

# 5. 调整显示样式(可选,让输出更贴近需求格式)
pd.set_option('display.max_columns', None)
print(df)

代码说明

  • 多级索引通过pd.MultiIndex.from_tuples创建,元组的每个元素对应索引的层级
  • 如果你已有Education-only和Medication Management列的数据集,需要先将数据拆解重组为对应5行6列的结构,再替换示例中的data变量
  • 设置names=["", ""]可以隐藏索引的层级名称,让输出更符合你给出的样式

内容的提问来源于stack exchange,提问作者sanjay kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:07:38