Python:按组组合列,然后组合行

Python:按组组合列,然后组合行,python,list,pandas,tuples,pandas-groupby,Python,List,Pandas,Tuples,Pandas Groupby,我有这个数据框: In [182]: data_set Out[182]: name parent distance rank 0 x aaa 10 1 1 x bbb 5 1 2 x fff 3 2 3 y aaa 2 2 4 y bbb 10 1 5 z ccc 8 2

我有这个数据框:

In [182]: data_set
Out[182]: 
  name  parent  distance  rank
0  x     aaa      10        1
1  x     bbb      5         1
2  x     fff      3         2
3  y     aaa      2         2
4  y     bbb      10        1
5  z     ccc      8         2 
我想将其重塑为:

  name          Combined
  x     ('aaa',10,1),('bbb',5,1),('fff',3,2)
  y     ('aaa',2,2),('bbb',10,1)
  z     ('ccc',8,2)
然后我想把它转换成带有两列的
name
组合的
数据帧3x2

我想使用
zip
group
,但它们返回不同的输出

首先将列组合到
元组
,然后将
groupby
组合到
列表

df['combined'] = df[['parent', 'distance', 'rank']].apply(tuple, axis=1)

res = df.groupby('name')['combined'].apply(list).reset_index()

print(res)

  name                                  combined
0    x  [(aaa, 10, 1), (bbb, 5, 1), (fff, 3, 2)]
1    y               [(aaa, 2, 2), (bbb, 10, 1)]
2    z                             [(ccc, 8, 2)]

使用
groupby
apply

df.groupby('name')[['parent','distance','rank']].apply(lambda x : x.values.tolist())
Out[14]: 
name
x    [[aaa, 10, 1], [bbb, 5, 1], [fff, 3, 2]]
y                 [[aaa, 2, 2], [bbb, 10, 1]]
z                               [[ccc, 8, 2]]
dtype: object

谢谢@Wen!您的解决方案工作正常,但它返回“series”而不是dataframe。谢谢@jpp。您的解决方案运行良好,输出正是我想要的!