我有一个数据框,如下所示
df
cust_id product score
1 bat 0.8
2 ball 0.3
2 phone 0.6
3 tv 1.0
2 bat 1.0
4 phone 0.2
1 ball 0.6
从上面我想准备下面的数据框架.
注:词典应按分值降序排序
Expected Output:
cust_id product_dict
1 {'bat': 0.8, 'ball':0.6}
2 {'bat': 1.0, 'phone':0.6, 'ball':0.3}
3 {'tv': 1.0}
4 {'phone':0.2}
我try 了下面的代码,但不起作用.
s = df.groupby(['cust_id','product'])['score'].apply(list)
d = {x: s.xs(x).to_dict() for x in s.index.levels[0]}
df1 = df.groupby('cust_id').agg(num_of_products=('product','nunique'))
df1.insert(2, 'product_dict', df1.index.map(d))
df1 = df1.reset_index()