组合相似的数据帧行

2024-09-28 15:29:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在有一个像这样的数据帧

User    Date     FeatureA FeatureB
John    DateA      1        2
John    DateB      3        5

不管怎样,我能把这两行合并成一行吗

  User    Date1    Date2    FeatureA1 FeatureB1 FeatureA2 FeatureB2
  John    DateA    DateB        1        2          3        5

Tags: 数据datejohnuserdate1date2featurebfeaturea
1条回答
网友
1楼 · 发布于 2024-09-28 15:29:34

我认为需要:

g = df.groupby(['User']).cumcount()
df = df.set_index(['User', g]).unstack()
df.columns = ['{}{}'.format(i, j+1) for i, j in df.columns]
df = df.reset_index()
print (df)
   User  Date1  Date2  FeatureA1  FeatureA2  FeatureB1  FeatureB2
0  John  DateA  DateB          1          3          2          5

说明:

  1. 使用^{}Users获取每个组的计数
  2. 通过^{}创建MultiIndex
  3. 重塑^{}
  4. 列中的扁平化MultiIndex
  5. 通过^{}index转换为列

相关问题 更多 >