首页 > 解决方案 > 带有 dict.update() 的 Pandas groupby 函数

问题描述

我正在尝试对每个元素使用带有 dict.update() 函数的 Pandas groupby 函数。数据框中的示例(仅用于说明):

        A                                            B
0   icon1   {'ap1': {'item' : 1}, 'ap2': {'item' : 2}}

1   icon1                        {'ap3': {'item' : 3}}

我想要做的是设置类似

df = df.groupby('A')['B'].apply(', '.join).reset_index()

python', '.join我需要按“A”列分组并更新“B”列中的每个元素,而不是使用 。我试过使用地图功能,但我无法实现任何有用的东西。

结果应该是:

        A                                                                 B
0   icon1   {'ap1': {'item' : 1}, 'ap2': {'item' : 2}, 'ap3': {'item' : 3}}

如果不从 dict 更改项目类型,这甚至可能吗?

标签: pythonpandas

解决方案


使用 dict 理解

df.groupby('A').B.agg(lambda s: {k:v for a in s for k, v in a.items()}).reset_index()

        A                                                                 B
0   icon1   {'ap1': {'item' : 1}, 'ap2': {'item' : 2}, 'ap3': {'item' : 3}}

推荐阅读