首页 > 解决方案 > Sum together certain values in a row

问题描述

I'm working in python, and have a dataframe(df), which includes the column 'COUNTERPARTYNAME'. There are different counterparties in this column, like 'A', 'B', 'C', etc... There is also another column called MTM, which is made up of numbers.

COUNTERPARTYNAME                   NPV          
0     A                            90                

1     B                            85                    

2     A                            130                     

3     C                            90    

4     B                            105

5     A                            75
...

...

Essentially, I'm looking to add a column to my dataframe that would have the sum of all the NPV's for the corresponding COUNTERPARTYNAME in that row.

My expected result would be like so:

    COUNTERPARTYNAME               NPV                 SUM(NPV)      
0     A                            90                  295

1     B                            85                  190  

2     A                            130                 295 

3     C                            90                  90

4     B                            105                 190

5     A                            75                  295
...

Thanks!

标签: pythonpandas

解决方案


Use GroupBy.transform:

df['SUM(NPV)'] = df.groupby('COUNTERPARTYNAME')['NPV'].transform('sum')

推荐阅读