如何使用python pandas对列进行分组并按条件计算值? [英] How to groupby a column and count the values on condition using python pandas?

查看:2143
本文介绍了如何使用python pandas对列进行分组并按条件计算值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入:

df=pd.DataFrame({
    'BusId':['abc1','abc2','abc3','abc1','abc2','abc4'],
    "Fair":[5,6,7,10,5,4]
})

需要按BusId分组,并需要以下输出

Need to group by BusId and need the following output

输出:

BusId   Count of Fair>=5    Count of Fair>=10
abc1    2                         1
abc2    1                         0
abc3    1                         0
abc4    0                         0

感谢您的帮助.

推荐答案

在系列中使用agg并带有两个辅助函数来对每个阈值以上的值进行计数.

Using agg on your series with two helper functions to count the values above each of your thresholds.

但是,在将来的pandas版本中,我在此所做的关于系列的聚合将被弃用.

However, aggregation on a Series as I am doing here will be deprecated in a future version of pandas.

df.groupby('BusId').Fair.agg({
    'gt5': lambda x: (x>=5).sum(),
    'gt10': lambda x: (x>=10).sum()
})

       gt5  gt10
BusId
abc1     2     1
abc2     2     0
abc3     1     0
abc4     0     0

您也可以删除对lambda的使用:

You could also remove the use of lambda:

out = df.assign(gt5=df.Fair.ge(5), gt10=df.Fair.ge(10))
out.groupby('BusId').agg({'gt5': 'sum', 'gt10': 'sum'}).astype(int)

       gt5  gt10
BusId
abc1     2     1
abc2     2     0
abc3     1     0
abc4     0     0

第二种方法会稍快一些:

The second approach will be slightly faster:

%%timeit
df.groupby('BusId').Fair.agg({
    'gt5': lambda x: (x>=5).sum(),
    'gt10': lambda x: (x>=10).sum()
})

5.05 ms ± 69 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit
out = df.assign(gt5=df.Fair.ge(5), gt10=df.Fair.ge(10))
out.groupby('BusId').agg({'gt5': 'sum', 'gt10': 'sum'}).astype(int)

3.76 ms ± 44.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

这篇关于如何使用python pandas对列进行分组并按条件计算值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆