我有一個數據框,其中有一列包含類別,另一列包含單詞。單詞可以在不同類別中重復,因此可能存在重復項。但是,我想將這些重復項放在字典中,如下所示:數據框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
提交
取消