Numpy:找到范围内的元素

时间:2012-12-13 21:56:39

标签: python numpy

我有一些数字,例如,

a = [1, 3, 5, 6, 9, 10, 14, 15, 56]  

我想找到特定范围内的所有元素。例如,如果范围是(6,10),答案应该是(3,4,5)。是否有内置函数来执行此操作?

12 个答案:

答案 0 :(得分:94)

您可以使用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]),)

答案 1 :(得分:44)

在@ deinonychusaur的回复中,但更紧凑:

In [7]: np.where((a >= 6) & (a <=10))
Out[7]: (array([3, 4, 5]),)

答案 2 :(得分:12)

我认为我会添加此内容,因为您提供的示例中的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])

答案 3 :(得分:7)

a = np.array([1,2,3,4,5,6,7,8,9])
b = a[(a>2) & (a<8)]

答案 4 :(得分:6)

答案摘要

为了解最佳答案,我们可以使用其他解决方案进行一些计时。 不幸的是,这个问题的位置不好,所以有不同问题的答案,在这里我尝试将答案指向同一问题。给定数组:

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])
# 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)")]',
]

结果

结果记录在下图中。最重要的是最快的解决方案。 enter image description here 如果要提取索引值而不是索引,则可以使用functions2执行测试,但结果几乎相同。

答案 5 :(得分:3)

此代码段返回两个值之间的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&lt; 10)也是如此。如果两个语句都为True(因为1x1 = 1)或False(因为0x0 = 0和1x0 = 0),则通过将这两个相乘得到一个带有True的数组。

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

当然,你可以通过例如

来说明这一点
...*(1-a<10) 

类似于“和不”声明。

答案 6 :(得分:1)

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]  

答案 7 :(得分:1)

其他方法是:

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

返回:

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

有时对于掩盖时间序列,向量等很有用。

答案 8 :(得分:1)

想将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)

仅对具有数百万个的较大阵列有意义,或者如果您达到内存限制。

答案 9 :(得分:0)

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

答案 10 :(得分:0)

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

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)

答案 11 :(得分:-2)

You can use np.clip() to achieve the same:

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

However, it holds the values less than and greater than 6 and 10 respectively.