简体   繁体   中英

Sum of specific values of specific columns in pandas

I have a dataset which contains:

Column_A   Column_B   Column_C
1          55         23
1          65         14  
2          32         54
2          25         13  
3          69         28
3          14         56

Desired output:

Sum of 'Column_B' + 'Column_C' taking into account same values of Column_A

total_of_11 = 55+65+23+14

total_of_22 = 32+25+54+13

You can sum and then group:

res = df.eval('Total=Column_B + Column_C', inplace=False)\
        .groupby('Column_A')['Total'].sum().reset_index()

print(res)

   Column_A  Total
0         1    157
1         2    124
2         3    167

You can use pd.DataFrame.groupby on you Column_A

df.groupby('Column_A').sum().sum(axis=1)

Output

Column_A
1    157
2    124
3    167

set_index and sum

df.set_index('Column_A').sum(level=0).sum(1)
Out[989]: 
Column_A
1    157
2    124
3    167
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