python - 从 groupby 创建字典字典

标签 python pandas pandas-groupby

我有一个看起来像这样的数据框:

    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/

相关文章:

java - Web 应用程序测试中的完整字段从 Python/Eclipse/DyDev 中的映射文档调用数据

python - 如何将一系列对象转换为单个 DataFrame?

python - Pandas 中几个数据帧的异步 'read_csv' - 为什么不更快

python - Pandas 面板花式索引 : How to return (index of) all DataFrames in Panel based on Boolean of multiple columns in each df

python - 缺少多天数据时用 NaN 填充数据框

python - Pandas 计算 groupby 中的平均单词数

python - 基于连续时间步计算事件

Python Regex Sub - 在替换中使用匹配作为字典键

python - 如何使用 Pandas 替换 DataFrame 中的列条目并创建字典新旧值

python - MongoDB:将用户嵌入到评论中