programing

Numpy: 범위 내 요소의 인덱스 찾기

css3 2023. 7. 24. 22:45

Numpy: 범위 내 요소의 인덱스 찾기

예를 들어, 나는 숫자들의 숫자 배열을 가지고 있습니다.

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]),)

@deinonychusaur의 대답처럼, 그러나 훨씬 더 간결합니다.

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

답변 요약

가장 좋은 답변이 무엇인지 이해하기 위해 다른 솔루션을 사용하여 타이밍을 조정할 수 있습니다.유감스럽게도 질문이 잘 제시되지 않았기 때문에 다른 질문에 대한 답이 있습니다. 여기서는 동일한 질문에 대한 답을 제시하려고 합니다.배열이 지정된 경우:

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를 사용하여 검정을 수행할 수 있지만 결과는 거의 동일합니다.

제가 이걸 추가할 거라고 생각했어요. 왜냐하면.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])
a = np.array([1,2,3,4,5,6,7,8,9])
b = a[(a>2) & (a<8)]

다른 방법은 다음과 같습니다.

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

다음을 반환합니다.

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

때때로 시계열, 벡터 등을 마스킹하는 데 유용합니다.

이 코드 조각은 두 값 사이의 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(참) 배열을 얻을 수 있습니다.

part a[...]는 대괄호 사이의 배열이 True 문을 반환하는 배열 a의 모든 값을 반환합니다.

물론 당신은 예를 들어 이렇게 말함으로써 이것을 더 복잡하게 만들 수 있습니다.

...*(1-a<10) 

이는 "및 아님" 문과 유사합니다.

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

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,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)
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]  

사용할 수 있습니다.np.clip()동일한 목표 달성:

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

그러나 각각 6보다 작거나 큰 값과 10보다 큰 값을 유지합니다.

언급URL : https://stackoverflow.com/questions/13869173/numpy-find-index-of-the-elements-within-range