如何应用操作 nth和 sum
在数据帧上的单个 groupby 操作中?考虑以下数据 -
cust_id Qtr points_1 points_2
0 A 1 126.0095 126.009500
1 A 2 0.0000 126.009500
2 A 3 0.0000 126.009500
3 A 4 0.0000 126.009500
4 B 5 68.3600 131.364750
5 B 6 8.5751 139.939850
6 B 7 0.0000 139.939850
7 C 8 0.0000 139.939850
8 C 9 53.2800 123.249925
9 D 10 0.0000 123.249925
我可以使用 获取组中的最后一个元素
df.groupby('cust_id')['points_2'].nth(-1)
但我想生成如下所示的输出,其中我得到一列和另一组中的最后一个元素的总和。我尝试使用类似的东西:
df.groupby('cust_id').agg({'points_1' : 'sum', 'points_2' : 'nth(-1)'})
但显然,这不是我可以指定 nth
方法的正确方法。
我错过了什么?
points_1(SUM) points_2(last_in_the_group)
A 126.0095 126.0095
B 76.93 139.93
C 53.2800 123.2499
D 0.0000 123.2499
最佳答案
使用GroupBy.last
而不是 nth
:
df = df.groupby('cust_id').agg({'points_1' : 'sum', 'points_2' : 'last'})
print (df)
points_1 points_2
cust_id
A 126.0095 126.009500
B 76.9351 139.939850
C 53.2800 123.249925
D 0.0000 123.249925
关于python - 如何获取 Pandas 数据框中组中 B 列的最后一条记录和 A 列的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56541893/