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函数装饰器和函数