python - 组合相似的数据框行

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

最佳答案

我认为需要:

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. reset_indexindex 转换为列

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

相关文章:

python - 使用python中的rawpy模块将原始图像转换为tiff

algorithm - Pandas:求解时间序列数据集最高值的阈值

python - 附加到 HDFStore 失败,返回 "cannot match existing table structure"

python - 将函数应用于 DataFrame 中的每个单元格

python - pandas dataframe 列中每个对象的访问属性

python - 在 Windows 中安装 mlabwrap 时出错

python - 使用 Python 和 OpenCV 的中值滤波器

Python Pygame 错误

python - Pandas - 使用多索引划分形状不均匀的 df

Python:将代码应用于整个数据框列