python - Pandas:按最大值分组并在组上求和的最快方法
问题描述
这就是我想要实现的目标:
input:
B C D
A
x z 1 10
x z 2 11
x z 3 12
y s 4 13
y s 5 14
output:
B C D sum
A
x z 3 12 33
y s 5 14 27
我有以下代码。
import pandas as pd
df = pd.DataFrame({'A': ['x','x','x','y','y'],
'B': ['z','z','z','s','s'],
'C': [1,2,3,4,5],
'D': [10,11,12,13,14]})
df = df.set_index('A')
df['sum'] = df.groupby('A')['D'].transform('sum')
idx = df.groupby(['A'])['C'].transform(max) == df['C']
df= df[idx]
我正在一个相当大的数据框上执行此操作。不过这需要很长时间,尤其是第一组。有没有办法加快这个过程?因为我要做的就是对一个组求和,并保留不同列最大的行。
解决方案
总的来说,我相信您的方法有效,除了一些改进:
# no need to set_index. Do so on smaller/filtered data if needed
# df = df.set_index('A')
# this is good
df['sum'] = df.groupby('A')['D'].transform('sum')
# there's a bit difference between `'max'` and `max`.
# one is vectorized, one is not
idx = df.groupby(['A'])['C'].transform('max') == df['C']
df= df[idx]
另一个改进是你可以做lazy groupby:
groups = df.groupby('A')
df['sum'] = groups['D'].transform('sum')
idx = groups['C'].transform('max') == df['C']
df = df[idx]
推荐阅读
- hive - 同一查询中的计算列 - Spark , Hive
- c# - Unity Canvas“随屏幕大小缩放”使元素在较低分辨率下不可见
- javascript - Firebase 身份验证 - 自定义身份验证
- java - 如何使这个数字时钟代码在 Java 中正常工作?
- java - 我如何确定一个点是否在我的三角形内?
- c# - 将可空引用类型与泛型类型一起使用时收到警告
- jquery-ui - 当父母关闭时关闭所有孩子
- node.js - “ng --version” module.js:471 抛出错误
- c++ - 字符串比较未返回正确结果
- python - 避免在python中输入javascript鸭子检测到硒?