python-3.x - 使用 apply/lambda 将分组数据框转换为字典

标签 python-3.x pandas dictionary

我有一个这样的 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/

相关文章:

python - 将 int 转换为字符串以添加到 map python 的函数

python-3.x - Python Pandas : Best way to normalize data?

Python3.8 : What's the difference between ImportError and ModuleNotFoundError

python - 在 asyncio(和观察者模式)中链接协程

python - Pandas 中 DatetimeIndex 的矢量化构造

python - eval(dir()[0]) 在 python 中做什么

python - 从字典列表创建键集

python - Flask-SQLAlchemy: SAWarning: Identity map already had an identity for (object), 用新刷新的对象替换它

python - 使用 aggfunc=sum 的 Pandas Dataframes 值计算在几列上

pandas - 绘制数据框 Pandas 不工作