我想 reshape 具有重复行的数据框。数据来自 csv 文件,其中重复数据 block 。
举个例子:
Name 1st 2nd
0 Value1 a1 b1
1 Value2 a2 b2
2 Value3 a3 b3
3 Value1 a4 b4
4 Value2 a5 b5
5 Value3 a6 b6
应 reshape 为:
Name 1st 2nd 3rd 4th
Value1 a1 b1 a4 b4
Value2 a2 b2 a5 b5
Value3 a3 b3 a6 b6
您对如何做到这一点有什么建议吗? 我已经看过这个thread ,但是我不知道如何将这种方法转化为我的问题,因为在 groupby 所在的列右侧有多个列。
最佳答案
您可以使用set_index
和 stack
将两列合并为一列,cumcount
获取新的列标签,以及 pivot
进行 reshape :
# Stack the 1st and 2nd columns, and use cumcount to get the new column labels.
df = df.set_index('Name').stack().reset_index(level=1, drop=True).to_frame()
df['new_col'] = df.groupby(level='Name').cumcount()
# Perform a pivot to get the desired shape.
df = df.pivot(columns='new_col', values=0)
# Formatting.
df = df.reset_index().rename_axis(None, 1)
结果输出:
Name 0 1 2 3
0 Value1 a1 b1 a4 b4
1 Value2 a2 b2 a5 b5
2 Value3 a3 b3 a6 b6
关于python - Pandas reshape 重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43595091/