Python pandas - Dataframe 使用 pd.groupby().agg() 获得第二高值

标签 python pandas numpy aggregate

我有一个 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/

相关文章:

python - 使用 python (django) 进行 AWS Elastic Beanstalk 日志记录

python - 使用 NaN 添加两个系列

python - 对齐没有公共(public)索引的 pandas DataFrame

Python pandas groupby 箱线图重叠

python - 根据其他列获取 Pandas 累积总和

python - 解码txt文件中的字节字符串 - Python 3

python - pickle numpy数组的子类时保留自定义属性

python - 类型错误 : __init__() got an unexpected keyword argument 'type' in argparse

python - 高效增量实现poset

python - 具有两个条件的 if 语句