我有一个 DF [名为 cleanData],其中包含一些值和 2 列,分别是 custom_critirea 和total_count。
这是我的 DF 的一部分:
CUSTOM_CRITERIA TOTAL_CODE_SERVED_COUNT
8 2768012 27
9 3307322 1
10 3270374 2
11 3353569 4
12 3423432 660
13 1737751 0
14 3564415 5
15 3593988 1
16 3593981 2
17 3603423 48367
18 3483162 6
19 3603380 3
20 3483062 2
21 3617505 2363
22 3617633 11
23 3607897 7
24 3619532 1
28 3633518 3
29 3653760 22
30 3653625 ...
我现在拥有的是:
aggMap = {'TOTAL_CODE_SERVED_COUNT': ['sum', 'max']}
cleanData = cleanData.groupby('CUSTOM_CRITERIA').agg(aggMap)
这给出了每个自定义条件的总代码服务计数的最大值和总和。
我现在想要实现的是从聚合中获得第二高的值
我需要这样的东西:
# myfunc should return for each group the second highest TOTAL_CODE_SERVED_COUNT
aggMap = {'TOTAL_CODE_SERVED_COUNT': ['sum', myfunc]}
cleanData = cleanData.groupby('CUSTOM_CRITERIA').agg(aggMap)
可以使用 df.groupby().agg() 实现吗?
最佳答案
示例数据:
cleanData = pd.DataFrame({
'TOTAL_CODE_SERVED_COUNT':[5,3,6,9,2,4,1],
'CUSTOM_CRITERIA':list('aaabbac')
}).sort_values('CUSTOM_CRITERIA')
print (cleanData)
TOTAL_CODE_SERVED_COUNT CUSTOM_CRITERIA
0 5 a
1 3 a
2 6 a
5 4 a
3 9 b
4 2 b
6 1 c
您可以对值进行排序并获取第二高的值,如果不存在则返回相同的值:
def myfunc(x):
y = np.sort(x)
return y[-2] if len(y) > 1 else x
aggMap = {'TOTAL_CODE_SERVED_COUNT': ['sum', myfunc]}
cleanData1 = cleanData.groupby('CUSTOM_CRITERIA').agg(aggMap)
print (cleanData1)
TOTAL_CODE_SERVED_COUNT
sum myfunc
CUSTOM_CRITERIA
a 18 5
b 11 2
c 1 1
如果不存在,则返回第二高的缺失值NaN
:
def myfunc(x):
y = np.sort(x)
return y[-2] if len(y) > 1 else np.nan
aggMap = {'TOTAL_CODE_SERVED_COUNT': ['sum', myfunc]}
cleanData2 = cleanData.groupby('CUSTOM_CRITERIA').agg(aggMap)
print (cleanData2)
TOTAL_CODE_SERVED_COUNT
sum myfunc
CUSTOM_CRITERIA
a 18 5.0
b 11 2.0
c 1 NaN
关于Python pandas - Dataframe 使用 pd.groupby().agg() 获得第二高值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62323334/