Groupby, sort and join

Viewed 82

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()
2 Answers

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))
)

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)
Related