简体   繁体   English

如何从 dataframe pandas 创建列表

[英]How to create a list from dataframe pandas

My dataset contains columns of usersID and itemsID that they have purchased.我的数据集包含他们购买的用户 ID 和项目 ID 列。 Each user might have purchased more than 1 item.每个用户可能购买了超过 1 件商品。

I neeed to make a list so that the key will be the userID and the values the itemsID he purchased for example if user_1 has purchased [item_20,item_25,item_32], my dataset contains 3 rows for this user as follows我需要制作一个列表,以便键是用户 ID 和他购买的项目 ID 的值,例如如果 user_1 购买了 [item_20,item_25,item_32],我的数据集包含该用户的 3 行,如下所示

row_1= 1,20 row_2= 1,25 row_3= 1,32

I want my list to have the fromat {1: [20,25,32]}我希望我的列表包含 fromat {1: [20,25,32]}

I want to creat a list for all the users in my dataset as the example above.如上例所示,我想为我的数据集中的所有用户创建一个列表。

if I understand correctly you want something like this!如果我理解正确你想要这样的东西!

Next time it would help to see what things you have tried下次看看你尝试了什么会有所帮助

df = pd.DataFrame({'user': ['K0', 'K0', 'K2', 'K3', 'K4', 'K5'],
                   'product': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']})

my_final_list={}
grouped_df=df.groupby(by=["user"])

for key, item in grouped_df:
    products_list=list(grouped_df.get_group(key)["product"])
    my_final_list[key]=products_list

print(my_final_list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM