conditional sums for pandas aggregate

前端 未结 2 1256
谎友^
谎友^ 2020-12-24 13:28

I just recently made the switch from R to python and have been having some trouble getting used to data frames again as opposed to using R\'s data.table. The problem I\'ve b

2条回答
  •  心在旅途
    2020-12-24 14:19

    To complement unutbu's answer, here's an approach using apply on the groupby object.

    >>> df.groupby('A_id').apply(lambda x: pd.Series(dict(
        sum_up=(x.B == 'up').sum(),
        sum_down=(x.B == 'down').sum(),
        over_200_up=((x.B == 'up') & (x.C > 200)).sum()
    )))
          over_200_up  sum_down  sum_up
    A_id                               
    a1              0         0       1
    a2              0         1       0
    a3              1         0       2
    a4              0         0       0
    a5              0         0       0
    

提交回复
热议问题