TigerJ
TigerJ

Reputation: 87

Groupby, sort and join

I have this data:

enter image description here

What I want to do is group this data by name, sort by number and join by the inter_type column.

So I want to have this kind of output:

enter image description here

I don't know how to do it. I know how to join them by group, but how to sort them? I have no idea how to implement here sort_values()?

df.groupby(['name'])['inter_type'].apply(lambda x: ','.join(x)).reset_index()

Upvotes: 2

Views: 635

Answers (2)

U13-Forward
U13-Forward

Reputation: 71580

Just use sort_value in the beginning on the number column. Also I modified your code to use agg with ','.join without lambda directly, it's more efficient and also it's shorter.

Code:

df.sort_values('number').groupby('name')['inter_type'].agg(','.join)

Upvotes: 2

mozway
mozway

Reputation: 260825

Please provide your dataframes as text, but something like this should work:

(df.sort_values(by='number')
   .groupby('name')
   ['inter_type'].apply(lambda x: ','.join(x))
)

Upvotes: 2

Related Questions