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

如何调整Pandas透视表以生成指定格式的输出结果?

Pandas透视表格式调整方案

问题分析

你当前用pd.pivot_table生成的结果存在多层列索引(因为values传的是列表["Percent"],导致列层级为(Percent, Date)),直接用reset_index(level=0, drop=True)会误删索引列items,需要先处理列索引结构,再调整索引与列的关系。

解决方法

方法1:先扁平化列索引,再按需重置索引

import pandas as pd
import numpy as np

# 生成原始透视表
result = pd.pivot_table(excel, values=["Percent"], columns='Date', index='items', aggfunc={"Percent":np.mean})

# 去掉列索引的顶层"Percent"层级,让日期直接作为列标题
result.columns = result.columns.droplevel(0)

# 若需要将索引列"items"转为普通列,执行以下代码
result = result.reset_index()

方法2:生成透视表时避免多层列索引

直接将values设为字符串而非列表,这样列不会生成多层索引,后续按需重置索引即可:

result = pd.pivot_table(excel, values="Percent", columns='Date', index='items', aggfunc=np.mean)
# 若要将"items"转为普通列
result = result.reset_index()

关键说明

  • 你之前用reset_index(level=0, drop=True)会删除索引的第0层(也就是items),这是错误的操作;如果要保留items作为列,只需直接调用reset_index()即可。
  • 当values传入列表时,Pandas会自动生成多层列索引,需要用droplevel(0)移除顶层的统计值名称(这里是Percent)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 05:12:06