简体   繁体   中英

How can i iterate for an specific column a sum of values based on a condition

This is the DataFrame and my code

import pandas as pd
 
    
data = {
    'year': ['2000','2000', '2000', '2000','2000','2000','2000','2000','2000','2000','2000','2000','2000','2000','2000',
            '2001','2001','2001','2001','2001','2001','2001','2001','2001','2001','2001','2001','2001','2001','2001',
            '2002','2002','2002','2002','2002','2002','2002','2002','2002','2002','2002','2002','2002','2002','2002'],     
    'type':[2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4],    
    'other_type':[0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4],    
    'Fee':[0,0,0,0,0,33,40,50,2,33,0,0,0,0,0,
                  30,50,10,200,45,0,0,0,0,0,0,0,0,0,0,
                 0,0,0,0,0,0,0,0,0,0,30,50,10,200,45]
}  
dfobj = pd.DataFrame(data)
dfobj.head()

I wanna make a filter based on condition of the column type, if the value is equal to 3, and if column other_type is 0 and 1, sum those values of column Fee. This is what i have

row_Sum = data.loc[(data['type']==3)&(data['other_type'] <2)].sum(axis=0,numeric_only=True)

But the problem is that all years are grouped into the result, i tried this but is but it is inefficient because is year per year, the real df is like thousands of rows and many columns and years.

row_Sum = dfobj.loc[(dfobj['year']==2000)&(dfobj['type']==3)&(dfobj['other_type'] <2)].sum(axis=0,numeric_only=True)

The main objective is to apply the sum condition for all the years.

Really grateful for any help you can provide, Thanks!

You can filter and use groupby.sum :

m = dfobj['type'].eq(3) & dfobj['other_type'].isin([0, 1])

out = dfobj.loc[m, 'Fee'].groupby(dfobj['year']).sum()

output:

year
2000    73
2001     0
2002     0
Name: Fee, dtype: int64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM