gpt4 book ai didi

python - pd.NamedAgg 中的矢量化百分位数

转载 作者:行者123 更新时间:2023-12-01 07:15:51 25 4
gpt4 key购买 nike

我在 pandas 0.25.1 中使用 pd.NamedAgg() 方法应用需要多个输入参数的 numpy 方法时遇到问题。

玩具示例:

## make df
animals = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
'height': [9.1, 6.0, 9.5, 34.0],
'weight': [7.9, 7.5, 9.9, 198.0]})
##Aggregate
animals.groupby("kind").agg(
pc95_height=pd.NamedAgg(column='height', aggfunc=np.percentile(q=0.95)),
mean_height=pd.NamedAgg(column='height', aggfunc=np.mean),
pc05_height=pd.NamedAgg(column='height', np.percentile(q=0.05)),
)

np.mean 可以正常工作,但任何版本的 np.percentile()np.percentile(p=0.95) 都会错误。

我可以使用 lambda 函数解决这个问题,但我更愿意避免这样做所固有的速度减慢。

任何关于如何使矢量化百分位数计算(和类似的)有效工作的帮助都非常感谢!

PS。更新了 agg,因为读者现在应该习惯 pd 0.25.1,特别是考虑到 1.0 即将推出......

##Aggregate V1
animals.groupby("kind").agg(
pc95_height=('height', np.percentile(q=0.95)),
mean_height=('height', np.mean),
pc05_height=('height', np.percentile(q=0.05)),
)
##Aggregate V2
animals.groupby("kind").agg(**{
'pc95_height':('height', np.percentile(q=0.95)),
'mean_height':('height', np.mean),
'pc05_height':('height', np.percentile(q=0.05))}
)

最佳答案

首先,您不需要那么冗长。只需传递一个元组就可以了。其次,由于 np.percentile 有参数,您可以定义自己的函数并说明这些参数是什么,或者使用 functools.partial (见下文)

def myfunc(s):
return np.percentile(s, q=0.95)

animals.groupby("kind").agg(mean_height=('height', 'mean'),
pc95_height=('height', myfunc))
<小时/>

您还可以使用部分

from functools import partial

perc95 = partial(np.percentile, q=95)

animals.groupby("kind").agg(mean_height=('height', 'mean'),
pc95_height=('height', perc95))

奇怪的是,pandas 似乎在将逻辑封装在匿名 lambda 中时遇到了问题,这可能是一个问题。

关于python - pd.NamedAgg 中的矢量化百分位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57961884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com