当前位置:  开发笔记 > 编程语言 > 正文

Pandas groupby function with dict.update()

如何解决《Pandasgroupbyfunctionwithdict.update()》经验,为你挑选了1个好方法。

I'm trying to use the Pandas groupby function with a dict.update() function to each element. An example in a data frame (just for illustration):

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

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

What I'm trying to do is set something like

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

But instead of using python', '.join, I need to groupby the 'A' column and update each element in the 'B' column. I've tried using the map function, but I was not able to achieve anything useful.

The outcome should be:

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

Is that even possible without changing the item type from dict?



1> rafaelc..:

Using dict comprehension

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}}

推荐阅读
N个小灰流_701
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有