我有一个数据框,如下所示

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()

推荐答案

您可以try :

df.set_index('product')
      .groupby('cust_id')
   .apply(lambda x: x['score'].to_dict())
   .reset_index(name='product_dict')
)

输出:

   cust_id                             product_dict
0        1                {'bat': 0.8, 'ball': 0.6}
1        2  {'ball': 0.3, 'phone': 0.6, 'bat': 1.0}
2        3                              {'tv': 1.0}
3        4                           {'phone': 0.2}

Note:要获得正确的顺序,只需在GROUPBY之前对数据进行排序:

(df.sort_values('score', ascending=False)
   .set_index('product')
   .groupby('cust_id')
   .apply(lambda x: x['score'].to_dict())
   .reset_index(name='product_dict')
)

输出:

   cust_id                             product_dict
0        1                {'bat': 0.8, 'ball': 0.6}
1        2  {'bat': 1.0, 'phone': 0.6, 'ball': 0.3}
2        3                              {'tv': 1.0}
3        4                           {'phone': 0.2}

Python-3.x相关问答推荐

Python gpsd客户端

像计数不显示在html和想知道如果我的模型设置正确

在循环中使用Print&S结束参数时出现奇怪的问题

Python GUI:tkinter应用程序作为Windows的实时桌面

aiogram机器人中处理文本输入异常而不是按钮点击的回调函数.

从一列字符串中提取子字符串并将它们放入列表中

提取图像中的背景并保存

移动所有列的数据帧值以使其单调递增

我正在使用 python 线程,当查询 mysql 时,代码似乎在运行并保持在无限循环中,没有返回任何错误

BeautifulSoup 和 pd.read_html - 如何将链接保存到最终数据框中的单独列中?

在数据类中创建类变量的正确方法

全局捕获快速 api 中的异常

如何使用 d.items() 更改 for 循环中的所有字典键?

类方法和实例方法同名

如何在 FastAPI 中的一条路由上捕获任意路径?

当默认 pip 为 pip2 时,升级 pip3 的正确格式是什么?

连接 dict 值,它们是列表

带有自定义标头的 urllib.urlretrieve

如何将python日志(log)级别名称转换为整数代码

如何使用 Celery 和 Django 将任务路由到不同的队列