Skip to main content
 首页 » 编程设计

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

2025年05月04日14Terrylee

这是我的数据:

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