在 pandas 数据框中使用groupby时如何连接设置? [英] how to concat sets when using groupby in pandas dataframe?
本文介绍了在 pandas 数据框中使用groupby时如何连接设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的数据框:
> df
a b
0 1 set([2, 3])
1 2 set([2, 3])
2 3 set([4, 5, 6])
3 1 set([1, 34, 3, 2])
现在,当我groupby
时,我想更新集合.如果它是list
,则没有问题.但是我的命令输出是:
Now when I groupby
, I want to update sets. If it was a list
there was no problem. But the output of my command is:
> df.groupby('a').sum()
a b
1 NaN
2 set([2, 3])
3 set([4, 5, 6])
我应该在groupby中做什么来更新集?我正在寻找的输出如下:
What should I do in groupby to update sets? The output I'm looking for is as below:
a b
1 set([2, 3, 1, 34])
2 set([2, 3])
3 set([4, 5, 6])
推荐答案
这可能接近您想要的
df.groupby('a').apply(lambda x: set.union(*x.b))
在这种情况下,它需要集合的并集.
In this case it takes the union of the sets.
如果需要保留列名,可以使用:
If you need to keep the column names you could use:
df.groupby('a').agg({'b':lambda x: set.union(*x)}).reset_index('a')
结果:
a b
0 1 set([1, 2, 3, 34])
1 2 set([2, 3])
2 3 set([4, 5, 6])
这篇关于在 pandas 数据框中使用groupby时如何连接设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文