通过A列获取B列分组的组大小和最小值 [英] Getting both group size and min of column B grouping by column A
本文介绍了通过A列获取B列分组的组大小和最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个DataFrame df
,我可以通过A列获得列A的大小
Given a DataFrame df
, I can obtain the size of groups by column A with
df.groupby(['columnA']).size()
df.groupby(['columnA']).agg({'columnB':min})
或(我猜是语法糖)
df.groupby(['columnA'])['columnB'].min()
但是我如何直接获得具有这两列的DataFrame?
but how can I obtain directly a DataFrame with such 2 columns?
在SQL中,如果您愿意,
In SQL, if you comfortable with it, this would be as simple as
SELECT count(columnA), min(columnB) FROM table GROUP BY columnA
预先感谢您提供任何线索。
Thanks in advance for any clue.
推荐答案
将它们都放在 agg
应该起作用,因为 agg
允许使用功能列表。
Placing both of them in agg
should work, since agg
permits a list of functions.
>>> df
columnA columnB columnC
0 cat1 3 400
1 cat1 2 20
2 cat1 5 3029
3 cat2 1 492
4 cat2 4 30
5 cat3 2 203
6 cat3 6 402
7 cat3 4 391
>>> df.groupby(['columnA']).columnB.agg(['size', 'min'])
size min
columnA
cat1 3 2
cat2 2 1
cat3 3 2
>>> df.groupby(['columnA']).agg(['size', 'min'])
columnB columnC
size min size min
columnA
cat1 3 2 3 20
cat2 2 1 2 30
cat3 3 2 3 203
agg
也接受列的dict->函数,因此,如果您想将一个函数分别映射到每个列,则可以使用某些方法(此处没有必要)
agg
also accepts a dict of columns -> functions, and so were you to want to map a function to each column individually you could do so with something (not necessary here) like
df.groupby(['columnA']).agg({'columnA':'size','columnB':'min'})
这篇关于通过A列获取B列分组的组大小和最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文