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

关于Pandas多索引DataFrame重塑函数的使用疑问

解决Pandas多索引下的DataFrame重塑问题

嘿,刚好碰到过类似的场景,我来帮你捋清楚怎么实现你想要的多索引pivot效果!

你现在的需求是把id1和id2共同作为行索引,同时将type列的取值(A/B/C)转成列,对应填充value的值,最终得到3行的DataFrame对吧?其实只需要调整pivot方法里的index参数就可以了——把index设置为一个包含id1和id2的列表,这样Pandas就会自动生成多级索引(MultiIndex)来匹配这两个列的唯一组合。

具体代码实现

先看你的原始数据:

import pandas as pd

d = {'id1': [1,1,1,1,1,1,2,2,2], 
     'id2': [1,1,1,2,2,2,1,1,1], 
     'value': [1,2,3,4,5,6,7,8,9], 
     'type':['A','B','C','A','B','C','A','B','C']}
tab = pd.DataFrame(data=d)

然后使用带多索引的pivot:

result = tab.pivot(index=['id1', 'id2'], columns='type', values='value')
print(result)

运行结果

你会得到这样的输出,正好是你想要的3行结构,行索引是id1和id2的唯一组合:

type        A  B  C
id1 id2           
1   1       1  2  3
    2       4  5  6
2   1       7  8  9

额外小提示

如果之后你想把多级索引拆成普通的列,可以用reset_index()方法:

result_reset = result.reset_index()
print(result_reset)

这样就会把id1和id2变回DataFrame的列,而不是索引了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:28:11