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

Python中透视DataFrame后无法移除MultiIndex的求助

问题解决:将Pivot后的MultiIndex DataFrame转为普通DataFrame

问题分析

你执行pivot后,DataFrame的行索引(index)是MultiIndex(id和Window),而列名是status_type的取值(snap、perf),status_type只是列索引的名称,并不是实际的列,所以你之前的drop('status_type', axis=1)会报错,因为找不到这一列。

正确代码

只需要调用reset_index()即可将行的MultiIndex展开为普通列,再可选移除列索引的名称让结构更简洁:

import pandas as pd
import numpy as np

# 数据
test_df = pd.DataFrame({"id": np.arange(0, 8), 
                   "Window": np.random.rand(8), 
                   "status_type" : ["snap","perf","snap","perf","snap","perf","snap","perf"],
                   "status_level": [1, 2, 20, 35, 10, 5, 42, 9],
                  })

# 透视并转换为普通DataFrame
result_df = (test_df
             .pivot(index=['id','Window'], columns='status_type', values='status_level')
             .reset_index()  # 将MultiIndex行转为普通列
             .rename_axis(columns=None)  # 移除列索引的名称(可选操作)
            )

print(result_df)

结果说明

执行后得到的result_df是标准普通DataFrame,包含id、Window、snap、perf四个常规列,无MultiIndex结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 08:12:07