python - 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!
解决方案
Use GroupBy.transform
:
df['SUM(NPV)'] = df.groupby('COUNTERPARTYNAME')['NPV'].transform('sum')
推荐阅读
- angular - Starting out with SASS, SCSS and Bootstrap in Angular project
- javascript - 将 Array.prototype.includes 与 Typescript 一起使用时,Jest 测试失败?
- node.js - Redis 简单消息队列(RSMQ)和公牛队列有什么区别?
- c# - 比较一个属性上的两个列表,不要添加重复项
- c++ - 类成员函数上的函数指针
- python - 在 Anaconda 环境中从 git 安装包,之后在 Python 中无法识别
- jquery - 在jQuery中获取具有数组值的名称属性的值
- ios - 在所有 iOS 设备上调整应用程序的布局
- javascript - 从 JSON 字符串中获取数组
- sat4j - 如何在 SAT4J 中随机(非确定性地)找到解决方案?