Numpy:查找范围内元素的索引
- 2025-04-16 08:56:00
- admin 原创
- 25
问题描述:
我有一个 numpy 数字数组,例如,
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
我想查找特定范围内元素的所有索引。例如,如果范围是 (6, 10),那么答案应该是 (3, 4, 5)。有没有内置函数可以做到这一点?
解决方案 1:
您可以使用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]),)
解决方案 2:
就像@deinonychusaur 的回复一样,但更加紧凑:
In [7]: np.where((a >= 6) & (a <=10))
Out[7]: (array([3, 4, 5]),)
解决方案 3:
答案摘要
为了理解最佳答案是什么,我们可以使用不同的解决方案进行一些计时。不幸的是,这个问题的提出方式不太好,所以答案指向了不同的问题。这里我尝试将答案指向同一个问题。给定一个数组:
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
对于较大的数组,速度可能会更快,但这需要对数组进行排序;对于条目数超过 10M 的数组,这ne.evaluate
可能是一个选择。因此,最好使用与您的数组大小相同的数组执行此测试:
如果您想要提取值而不是索引,则可以使用 functions2 执行测试,但结果几乎相同。
解决方案 4:
我想我会添加这个,因为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])
解决方案 5:
a = np.array([1,2,3,4,5,6,7,8,9])
b = a[(a>2) & (a<8)]
解决方案 6:
另一种方法是:
np.vectorize(lambda x: 6 <= x <= 10)(a)
返回:
array([False, False, False, True, True, True, False, False, False])
它有时对于掩盖时间序列、向量等很有用。
解决方案 7:
此代码片段返回 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),则返回 True;如果两个语句都为 False(因为 0x0 = 0 且 1x0 = 0),则返回 False。
部分 a[...] 返回数组 a 的所有值,其中括号之间的数组返回 True 语句。
当然,你也可以让情况变得更复杂,比如
...*(1-a<10)
类似于“and Not”语句。
解决方案 8:
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
np.argwhere((a>=6) & (a<=10))
解决方案 9:
想要将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)
仅对于具有数百万个较大阵列才有意义...或者当您达到内存限制时。
解决方案 10:
这可能不是最漂亮的,但适用于任何维度
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:
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]
解决方案 12:
您可以使用以下方法np.clip()
实现相同的目的:
a = [1, 3, 5, 6, 9, 10, 14, 15, 56]
np.clip(a,6,10)
但是,它分别保存小于 6 和大于 10 的值。
扫码咨询,免费领取项目管理大礼包!