提问人:zzzbbx 提问时间:12/14/2012 最后编辑:G Mzzzbbx 更新时间:3/26/2021 访问量:229754
Numpy:查找范围内元素的索引
Numpy: find index of the elements within range
问:
例如,我有一个数字数组,
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
我想在特定范围内找到元素的所有索引。例如,如果范围是 (6, 10),则答案应该是 (3, 4, 5)。是否有内置函数可以执行此操作?
答:
您可以使用来获取索引并设置两个条件: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]),)
评论
np.nonzero(np.logical_and(a>=6, a<=10))
我想我会添加这个,因为您给出的示例中已排序: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])
就像@deinonychusaur的回复一样,但更紧凑:
In [7]: np.where((a >= 6) & (a <=10))
Out[7]: (array([3, 4, 5]),)
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]
a = np.array([1,2,3,4,5,6,7,8,9])
b = a[(a>2) & (a<8)]
您可以使用来实现相同的目的:np.clip()
a = [1, 3, 5, 6, 9, 10, 14, 15, 56]
np.clip(a,6,10)
但是,它分别包含小于和大于 6 和 10 的值。
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
np.argwhere((a>=6) & (a<=10))
此代码片段返回两个值之间的 numpy 数组中的所有数字:
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56] )
a[(a>6)*(a<10)]
它的工作原理如下: (a>6) 返回一个 numpy 数组,其中 True (1) 和 False (0),(a<10) 也是如此。通过将这两者相乘,如果两个语句都是 True(因为 1x1 = 1)或 False(因为 0x0 = 0 和 1x0 = 0),则得到一个具有 True 的数组。
部分 a[...] 返回数组 a 的所有值,其中括号之间的数组返回 True 语句。
当然,你可以通过举例说
...*(1-a<10)
这类似于“和 Not”语句。
这可能不是最漂亮的,但适用于任何维度
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)
另一种方式是:
np.vectorize(lambda x: 6 <= x <= 10)(a)
返回:
array([False, False, False, True, True, True, False, False, False])
它有时可用于屏蔽时间序列、向量等。
想要将 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)
只对拥有数百万个的大型阵列才有意义......或者如果您达到内存限制。
答案摘要
为了理解什么是最佳答案,我们可以使用不同的解决方案进行一些计时。 不幸的是,这个问题没有很好地提出,所以有不同的问题的答案,在这里我试图将答案指向同一个问题。给定数组:
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它们可能因数组的大小而异。 对于较大的数组可能会更快,但它需要对数组进行排序,因为条目超过 10 M 的数组可能是一种选择。因此,最好使用与您的数组相同大小的数组执行此测试:sorted slice
ne.evaluate
如果要提取值而不是索引,则可以使用 functions2 执行测试,但结果几乎相同。
下一个:数据类型不懂
评论