我需要将DataFrame从长格式重塑为宽格式。数据的示例:
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一行。我试图通过创建数据透视表来解决问题,但我无法弄清楚如何:
对于如何推进此问题的任何建议表示赞赏!
答案 0 :(得分:2)
对我来说工作:
abc-numbr
答案 1 :(得分:0)
我用过不知道怎么做......
df1=df.groupby(['id','id_age'])['product','rank','result'].apply(lambda x : x.T.values.tolist()).apply(pd.Series)
df1.columns=['product','rank','result']
df1
Out[126]:
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]