I would like to convert some columns in a dataframe to list and some to set which has similar name The given dataframe, df:
Name id other list
0 ben 00005 abc [1000, A, 90]
1 alex 00006 gf [3000, B, 80]
2 linn 00007 jgj [600, C, 55]
3 luke 00009 gg [5000, D, 88]
4 alex 00001 gf [7000, R, 98]
5 ben 00002 abc [9000, S, 28]
6 ben 00003 abc [5000, T, 48]
The desired output, df1:
Name id other list
0 ben {00005, 0002,0003} abc [[1000, A, 90],[9000, S, 28],[5000, T, 48]]
1 alex {00006,0001} gf [3000, B, 80], [7000, R, 98]
2 linn {00007} jgj [600, C, 55]
3 luke {00009} gg [5000, D, 88]
You can use .groupby()
with .agg()
:
df.groupby("Name", as_index=False).agg({"id": set, "other": "first", "list": list})
This outputs:
Name id other list
0 alex {00001, 00006} gf [[3000, B, 80], [7000, R, 98]]
1 ben {00005, 00003, 00002} abc [[1000, A, 90], [9000, S, 28], [5000, T, 48]]
2 linn {00007} jgj [[600, C, 55]]
3 luke {00009} gg [[5000, D, 88]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.