如何用熊猫中的colum对相似的组进行分组

时间:2017-05-18 07:36:40

标签: pandas

人们!

我有这样的数据框:

ID | Name | Thing | belongs
---+------+---------+--------
 1   John     10       1
 2   Tom      10       2
 3   Tom      10       1
 4   John     10       2
 5   Bob      10       3

我无法弄清楚如何将其分组:

Tom,John    10  1,2
Bob.        10   3

我可以按用户分组,但生病得到两组而不是一组。

1 个答案:

答案 0 :(得分:0)

<强>设置

df = pd.DataFrame({'ID': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5},
 'Name': {0: 'John', 1: 'Tom', 2: 'Tom', 3: 'John', 4: 'Bob'},
 'Thing': {0: 10, 1: 10, 2: 10, 3: 10, 4: 10},
 'belongs': {0: 1, 1: 2, 2: 1, 3: 2, 4: 3}})

<强>解决方案

#group by name, thing and then concat belongs
df = df.groupby(by=['Name','Thing'])['belongs']\
               .apply(lambda x: ','.join(sorted(x.astype(str).tolist())))\
               .to_frame().reset_index()

df.groupby(by=['Thing','belongs'])['Name']\
          .apply(lambda x: ','.join(x.tolist())).to_frame().reset_index()

Out[1140]: 
   Thing belongs      Name
0     10     1,2  John,Tom
1     10       3       Bob