组合类似的数据帧行

时间:2018-03-21 05:59:54

标签: 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        5

1 个答案:

答案 0 :(得分:2)

I think need:

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

Explanation:

  1. Get count per groups by Users with cumcount
  2. set_index
  3. 创建MultiIndex
  4. 重塑unstack
  5. 列中的Flatenning MultiIndex
  6. reset_index
  7. index转换为列