带有 numpy 的数组的高效阈值过滤器

问题描述 投票:0回答:2

我需要过滤一个数组,去除低于某个阈值的元素。我现在的代码是这样的:

threshold = 5
a = numpy.array(range(10)) # testing data
b = numpy.array(filter(lambda x: x >= threshold, a))

问题是这会创建一个临时列表,使用带有 lambda 函数的过滤器(慢)。

因为这是一个非常简单的操作,也许有一个 numpy 函数可以有效地完成它,但我一直找不到它。

我认为另一种实现此目的的方法可能是对数组进行排序,找到阈值的索引并从该索引开始返回一个切片,但即使这对于小输入来说会更快(而且无论如何都不会引人注意) ,随着输入规模的增长,它的效率逐渐降低。

更新:我也测了一下,输入100.000.000条目时,排序+切片仍然是纯python过滤器的两倍。

r = numpy.random.uniform(0, 1, 100000000)

%timeit test1(r) # filter
# 1 loops, best of 3: 21.3 s per loop

%timeit test2(r) # sort and slice
# 1 loops, best of 3: 11.1 s per loop

%timeit test3(r) # boolean indexing
# 1 loops, best of 3: 1.26 s per loop
python arrays numpy filtering threshold
2个回答
113
投票

b = a[a>threshold]
这应该做

我测试如下:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

我有

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays


0
投票

您还可以使用

np.where
获取条件为 True 的索引并使用高级索引。

import numpy as np
b = a[np.where(a >= threshold)]

np.where
的一个有用功能是您可以使用它来替换值(例如,替换不满足阈值的值)。虽然
a[a <= 5] = 0
修改了
a
,但
np.where
返回一个具有相同形状的新数组,只是一些值(可能)发生了变化。

a = np.array([3, 7, 2, 6, 1])
b = np.where(a >= 5, a, 0)       # array([0, 7, 0, 6, 0])

在性能方面也很有竞争力

a, threshold = np.random.uniform(0,1,100000000), 0.5

%timeit a[a >= threshold]
# 1.22 s ± 92.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit a[np.where(a >= threshold)]
# 1.34 s ± 258 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
© www.soinside.com 2019 - 2024. All rights reserved.