我有一个这样的 df
A B C
0 11 one 5
1 11 two 7
2 11 three 9
3 22 one 11
4 22 two 13
我想将此 df 转换为字典,如下所示:
{11: [(one, 5), (two, 7), (three, 9)]
22: [(one, 11), (two, 13)]}
df_dict = df.groupby('A').apply(lambda y: {(x.B, x.C) for i, x in y.iterrows()})
我从这段代码中得到的实际结果:
11 {(one, 5), (two, 7), (three, 9)}
22 {(one, 11), (two, 13)}
最佳答案
尝试,
df.groupby('A').apply(lambda x: list(zip(x.B, x.C))).to_dict()
{11: [('one', 5), ('two', 7), ('three', 9)], 22: [('one', 11), ('two', 13)]}
关于python-3.x - 使用 apply/lambda 将分组数据框转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54261103/