我想找到每个产品id的计数,并创建一个以product_id为关键字和产品订购次数的字典


orders = {'U123':{'name':'Sumit Shukla', 'email':'ss@gmail.com', 'phone':8608538199, 'product':['p1', 'p2', 'p5']},
'U121':{'name':'Ajay', 'email':'aj@gmail.com', 'phone':7708538199, 'product':['p5', 'p2', 'p5']},
'U124':{'name':'Vijay', 'email':'vj@gmail.com', 'phone':870853819, 'product':['p1', 'p2', 'p3']},
'U126':{'name':'Rahul', 'email':'rh_gmail.com', 'phone':8607858189, 'product':['p1', 'p5', 'p5']},
'U183':{'name':'Shree', 'email':'shree@gmail.com', 'phone':8908938159, 'product':['p1', 'p1', 'p1']},
'U143':{'name':'shivani', 'email':'shivani@gmail', 'phone':855853019, 'product':['p5', 'p2', 'p5']}}

假设product_id为p1、p2等:

productsBought = {}
for productId in orders:

order = orders[productId]["product"]
for product in order:

try:

productsBought[product] += 1  #try to increment the amount of products with that id bought
except:

productsBought[product] = 1   #the product hasn't been bought before, set the number of purchases to 1.

这将给您留下一个格式为{产品id:购买次数}的字典

您可以使用:

df=pd.DataFrame(orders).T.reset_index().explode('product')
final=df.groupby('product').agg({'index':'count'}).reset_index().rename(columns={'index':'order_count'}).to_dict('records')
print(final)
'''
[{'product': 'p1', 'order_count': 6}, {'product': 'p2', 'order_count': 4}, {'product': 'p3', 'order_count': 1}, {'product': 'p5', 'order_count': 7}]
'''

最新更新