Reputation: 2464
I have a dataframe that looks something like this - with name,count
being strings
and id
being an int
.
name | count | id |
---|---|---|
abc | 123 | 01122 |
abc | 123 | 55432 |
abc | 123 | 33432 |
abc | 123 | 34786 |
xyz | 232 | 36126 |
xyz | 232 | 67437 |
Using pandas - I'm trying to get to something like
name | count | id |
---|---|---|
abc | 123 | 01122,55432,33432,34786 |
xyz | 232 | 36126,67437 |
I thought something like below would work - but it doesn't seem to actually join the list.
df.groupby(['name','count'])['id'].apply(lambda x: ','.join(map(str, x))).reset_index()
Upvotes: 0
Views: 139
Reputation: 24314
use astype()
+groupby()
+agg()
:
out=df.astype({'id':'str'}).groupby(['name','count'],as_index=False)['id'].agg(','.join)
#df.groupby(['name','count'],as_index=False)['id'].agg(lambda x: ','.join(map(str, x)))
output of out:
name count id
0 abc 123 1122,55432,33432,34786
1 xyz 232 36126,67437
Upvotes: 2