Python 组合相似的数据帧行

Python 组合相似的数据帧行,python,pandas,Python,Pandas,我现在有一个数据框,看起来像这样 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

我现在有一个数据框,看起来像这样

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
我认为需要:

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
说明:

  • 用户
    s获取每个组的计数
  • 创建多索引
  • 重塑
  • 在列中展开多索引
  • 通过将
    索引
    转换为列

  • 是否要合并具有相同
    用户的所有行?您是否可以拥有两行以上具有相同
    用户的行?@DyZ我想合并具有相同用户的所有行,以便数据帧只具有唯一的用户您对我问题的第二部分有答案吗?@DyZ对于您问题的第二部分,我不希望有超过一行具有相同的用户。您误解了我的问题。原始数据是否可以有两个以上的行具有相同的
    用户