按条件分组并计算子组的总和

Groupby on condition and calculate sum of subgroups

这是我的数据:

import numpy as np 
import pandas as pd
z = pd.DataFrame({'a':[1,1,1,2,2,3,3],'b':[3,4,5,6,7,8,9], 'c':[10,11,12,13,14,15,16]})
z

    a   b   c
0   1   3   10
1   1   4   11
2   1   5   12
3   2   6   13
4   2   7   14
5   3   8   15
6   3   9   16

问题:

如何对每个子组的不同元素进行计算?例如,对于每个组,我想提取列 'c' 中的任何元素,其对应的列 'b' 中的元素介于 4 和 9 之间,并将它们全部相加。

这是我写的代码:(它运行但我无法得到正确的结果)

gbz = z.groupby('a')
# For displaying the groups:
gbz.apply(lambda x: print(x))


list = []

def f(x):
    list_new = []
    for row in range(0,len(x)):
        if (x.iloc[row,0] > 4 and x.iloc[row,0] < 9):
            list_new.append(x.iloc[row,1])
    list.append(sum(list_new))

results = gbz.apply(f)

输出结果应该是这样的:

    a   c
0   1   12
1   2   27
2   3   15

可能最简单的方法是更改​​操作顺序,并首先根据您的条件进行过滤 - 它在 groupby 之后不会改变。

z.query('4 < b < 9').groupby('a', as_index=False).c.sum()

产生

   a   c
0  1  12
1  2  27
2  3  15

使用

In [2379]: z[z.b.between(4, 9, inclusive=False)].groupby('a', as_index=False).c.sum()
Out[2379]:
   a   c
0  1  12
1  2  27
2  3  15

或者

In [2384]: z[(4 < z.b) & (z.b < 9)].groupby('a', as_index=False).c.sum()
Out[2384]:
   a   c
0  1  12
1  2  27
2  3  15

你也可以先groupby

z = z.groupby('a').apply(lambda x: x.loc[x['b']\
           .between(4, 9, inclusive=False), 'c'].sum()).reset_index(name='c')
z

   a   c
0  1  12
1  2  27
2  3  15

或者您可以使用

z.groupby('a').apply(lambda x : sum(x.loc[(x['b']>4)&(x['b']<9),'c']))\
             .reset_index(name='c')
Out[775]: 
   a   c
0  1  12
1  2  27
2  3  15