Skip to main content
 首页 » 编程设计

python之合并相似的数据框行

2024年09月07日8jpfss

我目前有一个看起来像这样的数据框

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 

解释:

  1. 使用 cumcount 按用户获取每组计数
  2. 通过 set_index 创建 MultiIndex
  3. reshape unstack
  4. 在列中展开MultiIndex
  5. 将 index 转换为 reset_index 的列