我有一个数据框,其中有一列包含类别,另一列包含单词。单词可以在不同类别中重复,因此可能存在重复项。但是,我想将这些重复项放在字典中,如下所示:数据框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例如,如果设置为索引)。
添加回答
举报
0/150
提交
取消