Python pandas dataframe 将长变为宽、多列和常量值

标签 python pandas pivot reshape

我需要将 DataFrame 从长格式 reshape 为宽格式。数据示例:

import pandas as pd

df = pd.DataFrame({'id':[1,1,1,2,2,2,3,3], 'id_age':
30,30,30,23,23,23,29,29], 'product':['A','B','C','A','B','C','A','B'],
'rank':[1,2,3,3,1,2,2,1], 'result':['x','y','z','p','q','r','s','t']})

print(df)

   id  id_age product  rank result
0   1      30       A     1      x
1   1      30       B     2      y
2   1      30       C     3      z
3   2      23       A     3      p
4   2      23       B     1      q
5   2      23       C     2      r
6   3      29       A     2      s
7   3      29       B     1      t

所需的输出是

id  id_age    product       rank     result
0   1      30  [A, B, C]  [1, 2, 3]  [x, y, z]
1   2      23  [A, B, C]  [3, 1, 2]  [p, q, r]
2   3      29     [A, B]     [2, 1]     [s, t]

即每个 id 一行。我尝试通过创建数据透视表来解决问题,但我不知道如何:

  1. 针对多个列(产品、排名、结果) reshape 它
  2. 处理个体内恒定的值(value)观 (id_age)
  3. 使最终数据框中的列采用列表格式(顺序很重要,排名中列表的第一个值对应于给定个体结果中列表的第一个值)。

任何有关如何推进此问题的建议都将受到赞赏!

最佳答案

对我来说:

df = df.groupby(['id','id_age']).agg(tuple).applymap(list)
print (df)
             product       rank     result
id id_age                                 
1  30      [A, B, C]  [1, 2, 3]  [x, y, z]
2  23      [A, B, C]  [3, 1, 2]  [p, q, r]
3  29         [A, B]     [2, 1]     [s, t]

关于Python pandas dataframe 将长变为宽、多列和常量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47475354/

相关文章:

python - 在python中的文件中写入多行

python - 在 Django Admin 中显示组成员

python - 我如何使用 python-WikEdDiff?

python - App Engine 日志点有问题吗?

python - 使用局部加权回归 (LOESS/LOWESS) 预测新数据

python - Pandas ,将多列的多个功能应用于groupby对象

tsql - 我可以在 Microsoft SQL Server 中将 PIVOT 与内部联接结合使用吗?

sql - 如何转置表格并将结果分组?

sql - 交叉表转置查询请求

python - 使用条件在 pandas 中添加小时到日期/时间