gpt4 book ai didi

python - 合并相似的数据框行

转载 作者:太空宇宙 更新时间:2023-11-04 02:30:12 25 4
gpt4 key购买 nike

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

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 的列

关于python - 合并相似的数据框行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49399215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com