如何将Multi Index DataFrame的Product索引转为表头、保留Date为行索引?
如何将Multi Index DataFrame的Product索引转为表头并保留Date行索引
解决方案代码
import pandas as pd # 创建初始DataFrame并设置多级索引 df2 = pd.DataFrame({ 'Date': ['10-31','10-31','10-31','12-31','12-31','12-31'], 'Product': ['Apple','Pear','Banana','Apple','Pear','Banana'], 'Sales': [1, 0.8, 1.2, 2, 0.9, 1.7], 'Cost': [0.5, 0.3, 0.6, 0.4, 0.4, 0.7] }) df2.set_index(['Date', 'Product'], inplace=True) # 核心转换逻辑 result = df2.unstack('Product').swaplevel(axis=1).sort_index(axis=1) print(result)
转换步骤说明
unstack('Product'):将Product二级索引展开为列的层级,此时列结构为[Sales/Cost, Product],即先按数值列分类,再按产品分类。swaplevel(axis=1):交换列的两层索引,把Product移到表头第一层,Sales/Cost作为子表头,匹配目标结构。sort_index(axis=1):对列排序,确保同一产品下的Sales和Cost相邻排列。
最终输出结果
Product Apple Pear Banana Sales Cost Sales Cost Sales Cost Date 10-31 1.0 0.5 0.8 0.3 1.2 0.6 12-31 2.0 0.4 0.9 0.4 1.7 0.7
内容的提问来源于stack exchange,提问作者Matt
相关产品推荐
相关产品推荐

