[英]Pandas groupby and custom agg lambda function
I have a data frame and I want to aggregate a custom aggregation function.我有一个数据框,我想聚合一个自定义聚合 function。
Right now I have it like a predefined function, but I want to call it as a lambda function.现在我有它就像一个预定义的 function,但我想把它称为 lambda function。 Notice that the predefined function has a parameter that can be change.
请注意,预定义的 function 有一个可以更改的参数。
from sklearn.datasets import load_boston
import pandas as pd
import numpy as np
bunch = load_boston()
y = bunch.target
X = pd.DataFrame(bunch.data, columns=bunch.feature_names)
def percentile_func(y,PERCENTILE=50):
return np.percentile(y,PERCENTILE)
X.groupby('CHAS')['CRIM'].agg([percentile_func,'sum', 'count'])
Try this:尝试这个:
X.groupby('CHAS')['CRIM'].agg([lambda x: np.percentile(x, 50),'sum', 'count'])
You can use functools.partial
here.您可以在此处使用
functools.partial
。
from functools import partial
f = partial(percentile_func,PERCENTILE=50) # you can change PERCENTILE value accordingly.
X.groupby('CHAS')['CRIM'].agg([f,'sum', 'count'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.