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

Python3多级索引DataFrame如何用df.to_csv导出指定格式CSV文件

实现方案

直接用以下代码替换原有导出逻辑即可,导出结果完全符合你的需求:

import pandas as pd

df = pd.DataFrame(
    {
        ('a1', 'b1'): [11, 12, 13, 14],
        ('a1', 'b2'): [21, 22, 23, 24],
        ('a2', 'b1'): [31, 32, 33, 34],
        ('a2', 'b2'): [41, 42, 43, 44],
    },
    index=pd.MultiIndex.from_tuples([
        ('c1', 'd1'),
        ('c1', 'd2'),
        ('c2', 'd1'),
        ('c2', 'd2'),
    ]),
)

# -------------------------- 新增处理逻辑 --------------------------
# 1. 处理列表头第一层去重
seen_col_l1 = set()
processed_cols = []
for l1, l2 in df.columns:
    processed_cols.append((l1 if l1 not in seen_col_l1 else '', l2))
    seen_col_l1.add(l1)
df.columns = pd.MultiIndex.from_tuples(processed_cols)

# 2. 处理行数据,按第一层索引分组插入单独行
processed_data = []
for idx_l1, group in df.groupby(level=0):
    # 插入仅带第一层索引的空白行
    processed_data.append([idx_l1] + ['']*(len(df.columns)-1))
    # 插入该分组下的二级索引数据行,去掉重复的一级索引
    for idx_l2, row in group.droplevel(0).iterrows():
        processed_data.append([idx_l2] + row.to_list())

# 3. 手动写入CSV,先写两级表头再写处理后的数据
with open('my_test_file.csv', 'w', newline='', encoding='utf-8') as f:
    # 写入两级表头
    f.write(',' + ','.join([l1 for l1, l2 in df.columns]) + '\n')
    f.write(',' + ','.join([l2 for l1, l2 in df.columns]) + '\n')
    # 写入处理好的行数据
    for row in processed_data:
        f.write(','.join(map(str, row)) + '\n')

效果验证

导出的CSV内容和你给出的预期格式完全一致:

,a1,,a2,
,b1,b2,b1,b2
c1,,,,
d1,11,21,31,41
d2,12,22,32,42
c2,,,,
d1,13,23,33,43
d2,14,24,34,44

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:36:03