Reputation: 87
I have this data:
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:
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
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
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