猿问

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

我有一个数据框,其中有一列包含类别,另一列包含单词。单词可以在不同类别中重复,因此可能存在重复项。但是,我想将这些重复项放在字典中,如下所示:


数据框

category  | word       | score


happy     | tolerance  | 0.91

unhappy   | tolerance  | 0.12

angry     | kill       | 1.0

confident | tolerance  | 0.56

friendly  | tolerance  | 0.70

happy     | 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},

     ... 

}


www说
浏览 1592回答 1
1回答

慕村9548890

您可以直接构造结果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例如,如果设置为索引)。
随时随地看视频慕课网APP

相关分类

Python
我要回答