如何将Pandas多级索引DataFrame的结果列拆分为多列并排展示
解决Pandas多级索引DataFrame的逆透视问题
操作步骤
假设你的DataFrame结构类似下面的示例(多级索引为id、employee、date、week,仅包含result列):
import pandas as pd # 构造示例数据 data = {'result': ['CustomerA', 'Available', 'Active', 'CustomerB', 'Unavailable', 'Inactive']} index = pd.MultiIndex.from_tuples( [ (1, 'John', '2024-06-30', 27), (1, 'John', '2024-06-30', 27.1), (1, 'John', '2024-06-30', 27.2), (2, 'Jane', '2024-06-30', 27), (2, 'Jane', '2024-06-30', 27.1), (2, 'Jane', '2024-06-30', 27.2) ], names=['id', 'employee', 'date', 'week'] ) df = pd.DataFrame(data, index=index)
1. 重置索引
先把多级索引转换为普通列,方便后续处理:
df_reset = df.reset_index()
2. 映射week到目标字段
根据week的取值(如27对应customer、27.1对应availability、27.2对应status),建立映射关系并生成新的field列:
# 自定义week到字段的映射,根据你的实际情况调整 week_mapping = { 27: 'customer', 27.1: 'availability', 27.2: 'status' } df_reset['field'] = df_reset['week'].map(week_mapping)
如果week的小数部分有规律(比如.0对应customer、.1对应availability),也可以用逻辑推导生成field:
df_reset['field'] = df_reset['week'].apply( lambda x: ['customer', 'availability', 'status'][int((x - int(x)) * 10)] )
3. 执行逆透视(转置为宽表)
使用pivot或pivot_table将field列的不同值转为独立列,result作为对应列的值:
# 方法1:pivot(无重复数据时适用) df_final = df_reset.pivot( index=['id', 'employee', 'date'], columns='field', values='result' ).reset_index() # 移除列名的层级标签 df_final.columns.name = None # 方法2:pivot_table(有重复数据或缺失值时更稳定) df_final = df_reset.pivot_table( index=['id', 'employee', 'date'], columns='field', values='result', aggfunc='first' # 取第一个匹配值,可根据需求调整 ).reset_index() df_final.columns.name = None
执行后,df_final就是每行对应一条完整记录的格式,包含id、employee、date、customer、availability、status等列。
内容的提问来源于stack exchange,提问作者Treemaster
相关产品推荐
相关产品推荐

