agg

这篇博客介绍了Pandas库中如何使用NamedAgg进行多列聚合操作,包括不支持lambda函数时的解决方案。通过定义外部函数,如R1和R2,计算最大值与最小值的差以及最大值与中位数的差。此外,还展示了如何创建带参数的聚合函数,例如检查组内是否存在特定范围的数值。最后,通过装饰器技巧实现了同时使用多个聚合函数,其中包括一个带参数的函数,如检查是否至少有一个数值在指定范围内。
摘要由CSDN通过智能技术生成

1.利用NamedAgg函数进行多个聚合
注意:不支持lambda函数,但是可以使用外置的def函数

In [27]:
def R1(x):
    return x.max()-x.min()
def R2(x):
    return x.max()-x.median()
grouped_single['Math'].agg(min_score1=pd.NamedAgg(column='col1', aggfunc=R1),
                           max_score1=pd.NamedAgg(column='col2', aggfunc='max'),
                           range_score2=pd.NamedAgg(column='col3', aggfunc=R2)).head()
Out[27]:
min_score1	max_score1	range_score2
School			
S_1	65.5	97.0	33.5
S_2	62.8	95.5	39.4

2.带参数的聚合函数
判断是否组内数学分数至少有一个值在50-52之间:

In [28]:
def f(s,low,high):
    return s.between(low,high).max()
grouped_single['Math'].agg(f,50,52)
#.between返回的是一列布尔值
#.max作用于布尔列,返回true,.min作用于布尔列,返回false

Out[28]:
School
S_1    False
S_2     True
Name: Math, dtype: bool

3.如果需要使用多个函数,并且其中至少有一个带参数,则使用wrap技巧

n [29]:
def f_test(s,low,high):
    return s.between(low,high).max()
def agg_f(f_mul,name,*args,**kwargs):
    def wrapper(x):
        return f_mul(x,*args,**kwargs)
    wrapper.__name__ = name
    return wrapper
new_f = agg_f(f_test,'at_least_one_in_50_52',50,52)
grouped_single['Math'].agg([new_f,'mean']).head()
Out[29]:
at_least_one_in_50_52	mean
School		
S_1	False	63.746667
S_2	True	59.555000

https://www.cnblogs.com/eilinge/p/9705516.html
关于wrapper函数装饰器
https://www.runoob.com/w3cnote/python-func-decorators.html
关于python函数装饰器和函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值