为了账号安全,请及时绑定邮箱和手机立即绑定

如何将所有 pandas 重复项转换为字典?

如何将所有 pandas 重复项转换为字典?

www说 2023-08-22 15:18:43
我有一个数据框,其中有一列包含类别,另一列包含单词。单词可以在不同类别中重复,因此可能存在重复项。但是,我想将这些重复项放在字典中,如下所示:数据框category  | word       | scorehappy     | tolerance  | 0.91unhappy   | tolerance  | 0.12angry     | kill       | 1.0confident | tolerance  | 0.56friendly  | tolerance  | 0.70happy     | kill       | 0.01...预期字典:d = {    'tolerance' = {'happy': 0.91, 'angry': 0.01, 'confident': 0.56, 'friendly': 0.70},     'kill' = {'happy': 0.01, 'angry': 1.0, 'confident': 0.32, 'friendly': 0.016},     ... }
查看完整描述

1 回答

?
慕村9548890

TA贡献1884条经验 获得超4个赞

您可以直接构造结果dict,如下所示:


new_d = {}

for g, d in df.groupby('word'):

    new_d[g] = d.set_index('category')['score'].to_dict()

该pd.DataFrame.to_dict方法在传递时orient='index'不支持多个索引键(word例如,如果设置为索引)。


查看完整回答
反对 回复 2023-08-22
  • 1 回答
  • 0 关注
  • 1591 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信