有没有一种相当快速的方法可以对包含NaN值的数据执行np.percentile(ndarr, axis=0)
?在
对于np.median
,对应的bottleneck.nanmedian
(https://pypi.python.org/pypi/Bottleneck)相当不错。在
我对percentile提出的最好的方法是:
from bottleneck import nanrankdata, nanmax, nanargmin
def nanpercentile(x, q, axis):
ranks = nanrankdata(x, axis=axis)
peak = nanmax(ranks, axis=axis)
pct = ranks/peak / 100. # to make a percentile
wh = nanargmin(abs(pct-q),axis=axis)
return x[wh]
这行不通;真正需要的是用某种方法沿着axis
获取第n个元素,但我还没有找到numpy切片技巧来做到这一点。在
“相当快”意味着比循环指数更好,例如:
^{pr2}$这是有效的,但可能非常慢。在
np.ma
似乎没有按预期工作;它将nan
值视为inf
:
xm = np.ma.masked_where(np.isnan(x),x)
print np.percentile(xm,40,axis=2)
# array([[ 1.8, 5.6],
# [ 0.9, 7.8]])
您可以使用
as_strided()
,它位于numpy.lib.stride_tricks
中,操纵数组的跨步以更快地迭代它。在您的计算可以看作是在数组的(1,1,3)个窗口上操作。我喜欢使用一个广义函数(
sliding_window()
),它使用as_strided()
创建n个窗口的n。我在这里找到的-Efficient Overlapping Windows with Numpy;函数的功劳显然属于johnvinyard。这个博客页面很好地描述了正在发生的事情。在制作一些1x1x3窗口
应用```百分位()''-忽略NaN
^{pr2}$对结果进行数组:
让它恢复到您期望的形状
这应该更快。我很好奇它是否会-我没有任何现实世界的问题来测试它。在
在谷歌上搜索numpy as_striped会得到一些不错的结果:我把这个作为书签,http://scipy-lectures.github.io/advanced/advanced_numpy/
sliding_window()
来自Efficient Overlapping Windows with Numpy如果您不需要超快的解决方案,您可以先将数组转移到pandas DataFrame并执行分位数,然后返回numpy数组。在
np.nanpercentile
包含在numpy 1.9.0中http://docs.scipy.org/doc/numpy/reference/generated/numpy.nanpercentile.html
相关问题 更多 >
编程相关推荐