如何为binned_statistic创建用户定义的函数

时间:2015-08-22 19:16:44

标签: python numpy statistics scipy

我正在使用scipy stats包来沿轴取统计数据,但我在使用binned_statistic获取百分位统计数据时遇到问题。我已经推广了下面的代码,我试图在一系列x箱中使用x,y值来获取数据集的第10个百分点,并且它失败了。

我当然可以使用np.std来执行函数选项,例如中位数,甚至是numpy标准差。但是,我无法弄清楚如何使用np.percentile因为它需要2个参数(例如np.percentile(y, 10)),但它会给我一个ValueError: statistic not understood错误。

import numpy as np
import scipy.stats as scist

y_median = scist.binned_statistic(x,y,statistic='median',bins=20,range=[(0,5)])[0]

y_std = scist.binned_statistic(x,y,statistic=np.std,bins=20,range=[(0,5)])[0]

y_10 = scist.binned_statistic(x,y,statistic=np.percentile(10),bins=20,range=[(0,5)])[0]

print y_median
print y_std
print y_10

我很茫然,甚至玩过这样的用户定义函数,但没有运气:

def percentile10():
   return(np.percentile(y,10))

任何帮助,非常感谢。

感谢。

1 个答案:

答案 0 :(得分:5)

您定义的函数的问题在于它根本不需要参数!它需要采用与您的样本对应的y参数,如下所示:

def percentile10(y):
   return(np.percentile(y,10))

为简洁起见,您还可以使用lambda功能:

scist.binned_statistic(x, y, statistic=lambda y: np.percentile(y, 10), bins=20,
                       range=[(0, 5)])[0]
相关问题