112

我有一个 numpy 数字数组,例如,

a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])  

我想找到特定范围内元素的所有索引。例如,如果范围是 (6, 10),则答案应该是 (3, 4, 5)。是否有内置功能可以做到这一点?

4

12 回答 12

185

您可以使用np.where来获取索引并np.logical_and设置两个条件:

import numpy as np
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])

np.where(np.logical_and(a>=6, a<=10))
# returns (array([3, 4, 5]),)
于 2012-12-13T22:01:04.937 回答
73

正如@deinonychusaur 的回复,但更紧凑:

In [7]: np.where((a >= 6) & (a <=10))
Out[7]: (array([3, 4, 5]),)
于 2012-12-14T02:55:05.097 回答
17

我想我会添加这个,因为a在你给出的例子中是排序的:

import numpy as np
a = [1, 3, 5, 6, 9, 10, 14, 15, 56] 
start = np.searchsorted(a, 6, 'left')
end = np.searchsorted(a, 10, 'right')
rng = np.arange(start, end)
rng
# array([3, 4, 5])
于 2012-12-13T23:59:29.840 回答
17

答案摘要

为了了解什么是最佳答案,我们可以使用不同的解决方案进行一些计时。不幸的是,这个问题没有很好地提出,所以有不同问题的答案,在这里我试图指出同一个问题的答案。给定数组:

a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])

答案应该是某个范围内的元素的索引,我们假设包括在内,在本例中为 6 和 10。

answer = (3, 4, 5)

对应值 6、9、10。

要测试最佳答案,我们可以使用此代码。

import timeit
setup = """
import numpy as np
import numexpr as ne

a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
# or test it with an array of the similar size
# a = np.random.rand(100)*23 # change the number to the an estimate of your array size.

# we define the left and right limit
ll = 6
rl = 10

def sorted_slice(a,l,r):
    start = np.searchsorted(a, l, 'left')
    end = np.searchsorted(a, r, 'right')
    return np.arange(start,end)
"""

functions = ['sorted_slice(a,ll,rl)', # works only for sorted values
'np.where(np.logical_and(a>=ll, a<=rl))[0]',
'np.where((a >= ll) & (a <=rl))[0]',
'np.where((a>=ll)*(a<=rl))[0]',
'np.where(np.vectorize(lambda x: ll <= x <= rl)(a))[0]',
'np.argwhere((a>=ll) & (a<=rl)).T[0]', # we traspose for getting a single row
'np.where(ne.evaluate("(ll <= a) & (a <= rl)"))[0]',]

functions2 = [
   'a[np.logical_and(a>=ll, a<=rl)]',
   'a[(a>=ll) & (a<=rl)]',
   'a[(a>=ll)*(a<=rl)]',
   'a[np.vectorize(lambda x: ll <= x <= rl)(a)]',
   'a[ne.evaluate("(ll <= a) & (a <= rl)")]',
]

rdict = {}
for i in functions:
    rdict[i] = timeit.timeit(i,setup=setup,number=1000)
    print("%s -> %s s" %(i,rdict[i]))

print("Sorted:")
for w in sorted(rdict, key=rdict.get):
    print(w, rdict[w])

结果

正如@EZLearner 所指出的,在下图中报告了一个小数组(在顶部是最快的解决方案)的结果,它们可能会因数组的大小而异。sorted slice对于较大的数组可能会更快,但它需要对数组进行排序,对于具有超过 10 M 条目的数组ne.evaluate可能是一种选择。因此,使用与您的大小相同的数组执行此测试总是更好: 在此处输入图像描述

如果您想要提取值而不是索引,则可以使用 functions2 执行测试,但结果几乎相同。

于 2020-03-30T11:41:11.917 回答
15
a = np.array([1,2,3,4,5,6,7,8,9])
b = a[(a>2) & (a<8)]
于 2017-03-31T13:09:25.747 回答
5

此代码段返回两个值之间的 numpy 数组中的所有数字:

a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56] )
a[(a>6)*(a<10)]

它的工作原理如下:(a>6) 返回一个带有 True (1) 和 False (0) 的 numpy 数组,(a<10) 也是如此。通过将这两者相乘,您将得到一个数组,如果两个语句都为 True(因为 1x1 = 1)或 False(因为 0x0 = 0 和 1x0 = 0),则该数组为 True。

a[...] 部分返回数组 a 的所有值,其中括号之间的数组返回 True 语句。

当然,您可以通过说例如

...*(1-a<10) 

这类似于“and Not”语句。

于 2017-06-12T11:17:15.037 回答
5

另一种方法是:

np.vectorize(lambda x: 6 <= x <= 10)(a)

返回:

array([False, False, False,  True,  True,  True, False, False, False])

它有时对屏蔽时间序列、向量等很有用。

于 2020-02-27T16:39:25.910 回答
3
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
np.argwhere((a>=6) & (a<=10))
于 2017-05-30T20:22:26.943 回答
3

想要将numexpr添加到组合中:

import numpy as np
import numexpr as ne

a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])  

np.where(ne.evaluate("(6 <= a) & (a <= 10)"))[0]
# array([3, 4, 5], dtype=int64)

只有数百万的大型数组才有意义......或者如果你达到内存限制。

于 2020-03-18T15:19:07.710 回答
1

这可能不是最漂亮的,但适用于任何维度

a = np.array([[-1,2], [1,5], [6,7], [5,2], [3,4], [0, 0], [-1,-1]])
ranges = (0,4), (0,4) 

def conditionRange(X : np.ndarray, ranges : list) -> np.ndarray:
    idx = set()
    for column, r in enumerate(ranges):
        tmp = np.where(np.logical_and(X[:, column] >= r[0], X[:, column] <= r[1]))[0]
        if idx:
            idx = idx & set(tmp)
        else:
            idx = set(tmp)
    idx = np.array(list(idx))
    return X[idx, :]

b = conditionRange(a, ranges)
print(b)
于 2019-03-07T11:05:10.817 回答
0
s=[52, 33, 70, 39, 57, 59, 7, 2, 46, 69, 11, 74, 58, 60, 63, 43, 75, 92, 65, 19, 1, 79, 22, 38, 26, 3, 66, 88, 9, 15, 28, 44, 67, 87, 21, 49, 85, 32, 89, 77, 47, 93, 35, 12, 73, 76, 50, 45, 5, 29, 97, 94, 95, 56, 48, 71, 54, 55, 51, 23, 84, 80, 62, 30, 13, 34]

dic={}

for i in range(0,len(s),10):
    dic[i,i+10]=list(filter(lambda x:((x>=i)&(x<i+10)),s))
print(dic)

for keys,values in dic.items():
    print(keys)
    print(values)

输出:

(0, 10)
[7, 2, 1, 3, 9, 5]
(20, 30)
[22, 26, 28, 21, 29, 23]
(30, 40)
[33, 39, 38, 32, 35, 30, 34]
(10, 20)
[11, 19, 15, 12, 13]
(40, 50)
[46, 43, 44, 49, 47, 45, 48]
(60, 70)
[69, 60, 63, 65, 66, 67, 62]
(50, 60)
[52, 57, 59, 58, 50, 56, 54, 55, 51]  
于 2016-07-08T06:27:13.147 回答
-4

您可以使用np.clip()来实现相同的目的:

a = [1, 3, 5, 6, 9, 10, 14, 15, 56]  
np.clip(a,6,10)

但是,它分别保存小于和大于 6 和 10 的值。

于 2017-04-10T02:06:05.483 回答