【问题标题】:Interval containing specified percent of values包含指定百分比值的区间
【发布时间】:2014-12-03 13:20:14
【问题描述】:
对于 numpy 或 scipy,是否有任何现有方法可以返回包含一维数组中指定百分比值的区间的端点?我意识到这很容易自己写,但它似乎是可以内置的那种东西,虽然我找不到它。
例如:
>>> import numpy as np
>>> x = np.random.randn(100000)
>>> print(np.bounding_interval(x, 0.68))
会给approximately(-1, 1)
【问题讨论】:
标签:
python
numpy
statistics
【解决方案1】:
你可以使用np.percentile:
In [29]: x = np.random.randn(100000)
In [30]: p = 0.68
In [31]: lo = 50*(1 - p)
In [32]: hi = 50*(1 + p)
In [33]: np.percentile(x, [lo, hi])
Out[33]: array([-0.99206523, 1.0006089 ])
还有scipy.stats.scoreatpercentile:
In [34]: scoreatpercentile(x, [lo, hi])
Out[34]: array([-0.99206523, 1.0006089 ])
【解决方案2】:
我不知道有什么内置函数可以做到这一点,但您可以使用 math 包编写一个来指定近似索引,如下所示:
from __future__ import division
import math
import numpy as np
def bound_interval(arr_in, interval):
lhs = (1 - interval) / 2 # Specify left-hand side chunk to exclude
rhs = 1 - lhs # and the right-hand side
sorted = np.sort(arr_in)
lower = sorted[math.floor(lhs * len(arr_in))] # use floor to get index
upper = sorted[math.floor(rhs * len(arr_in))]
return (lower, upper)
在你指定的数组上,我得到了间隔(-0.99072237819851039, 0.98691691784955549)。非常接近(-1, 1)!