我有一个看起来像这样的数据框:
Friend A Friend B Score
0 Walter John 22
1 Walter Jack 32
2 Fred John 10
3 Caleb Jack 5
我想生产的是:
{"Walter": {"John": 22, "Jack": 32}, "Fred": {"John": 10}, "Caleb": {"Jack": 5}}
到目前为止,我所拥有的是:
x = Network.groupby("Friend A")[["Friend A", "Friend B", "Score"]]
我试过做以下事情:
x.apply(list).to_dict()
但这不是我想要的结果。我怎样才能达到这个结果?
最佳答案
In [17]: df.groupby("Friend A").apply(lambda x: x.set_index("Friend B")['Score'].to_dict()).to_dict()
Out[17]:
{'Caleb': {'Jack': 5},
'Fred': {'John': 10},
'Walter': {'Jack': 32, 'John': 22}}
关于python - 从 groupby 创建字典字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60963409/