Combine rows by id

此生再无相见时 提交于 2019-12-11 04:47:43

问题


I have the following types of data. How to combine rows by id, and the type record a separate column (all types 10) (or record types, separated by commas in a single column)

id,type,value
1,8,value1
1,2,value1
1,7,value1
1,3,value1
1,10,value1
2,3,value1
2,8,value1
2,7,value1

desired output:

 id        type    value 
0   1  8,2,7,3,10  value1 
1   2       3,8,7  value1

回答1:


I think you can use groupby with apply join, but first convert int to str:

df = df.groupby('id')['type'].apply(lambda x: ','.join(x.astype(str))).reset_index()
print (df)
   id        type
0   1  8,2,7,3,10
1   2       3,8,7


来源:https://stackoverflow.com/questions/40792089/combine-rows-by-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!