所以我得到了一个 DataFrame,如下所示:
Col_0 Col_1
Index_1
A 0 2
A 3 1
A 2 2
B 3 1
B 4 3
B 5 1
我想将其 reshape 为以下格式:
Col_0 Col_1
A B A B
0 3 2 1
3 4 1 3
2 5 2 1
我尝试过pandas.pivot
, pandas.unstack
, pandas.groupby
。这些都不起作用。谁能帮我解决一下吗?非常感谢。
最佳答案
使用cumcount
创建索引,然后pivot
:
df['idx'] = df.groupby(df.index).cumcount()
df.reset_index().pivot(index='idx', columns='Index_1').rename_axis(None)
输出:
Col_0 Col_1
Index_1 A B A B
0 0 3 2 1
1 3 4 1 3
2 2 5 2 1
关于python - 透视/取消堆叠具有重复条目的 DataFrame,无需聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56317655/