Programing

Numpy array, 여러 조건을 만족하는 인덱스를 선택하는 방법은 무엇입니까?

crosscheck 2020. 7. 10. 08:00
반응형

Numpy array, 여러 조건을 만족하는 인덱스를 선택하는 방법은 무엇입니까?


내가 NumPy와 배열을 가정 x = [5, 2, 3, 1, 4, 5], y = ['f', 'o', 'o', 'b', 'a', 'r']. 1보다 크고 5보다 작은 요소에 y해당하는 요소를 선택하고 싶습니다 x.

나는 시도했다

x = array([5, 2, 3, 1, 4, 5])
y = array(['f','o','o','b','a','r'])
output = y[x > 1 & x < 5] # desired output is ['o','o','a']

그러나 이것은 작동하지 않습니다. 어떻게해야합니까?


괄호를 추가하면 표현식이 작동합니다.

>>> y[(1 < x) & (x < 5)]
array(['o', 'o', 'a'], 
      dtype='|S1')

IMO 영업 이익은 실제로 원하지 않는다 np.bitwise_and()(일명 &) 실제로 원하는 np.logical_and()그들과 같은 논리 값 비교되기 때문에 TrueFalse-에 SO 게시물을 참조 비트 대 논리적 차이를 볼 수 있습니다.

>>> x = array([5, 2, 3, 1, 4, 5])
>>> y = array(['f','o','o','b','a','r'])
>>> output = y[np.logical_and(x > 1, x < 5)] # desired output is ['o','o','a']
>>> output
array(['o', 'o', 'a'],
      dtype='|S1')

이와 동등한 방법 np.all()axis인수를 적절하게 설정하는 것 입니다.

>>> output = y[np.all([x > 1, x < 5], axis=0)] # desired output is ['o','o','a']
>>> output
array(['o', 'o', 'a'],
      dtype='|S1')

숫자로 :

>>> %timeit (a < b) & (b < c)
The slowest run took 32.97 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 1.15 µs per loop

>>> %timeit np.logical_and(a < b, b < c)
The slowest run took 32.59 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.17 µs per loop

>>> %timeit np.all([a < b, b < c], 0)
The slowest run took 67.47 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 5.06 µs per loop

그래서 사용은 np.all()느리지 만 &logical_and거의 동일하다.


@JF Sebastian과 @Mark Mikofski의 답변에 세부 사항을 추가하십시오 :
배열의 실제 값이 아닌 해당 색인을 얻으려면 다음 코드가 수행됩니다.

여러 (모든) 조건을 만족시키는 경우 :

select_indices = np.where( np.logical_and( x > 1, x < 5) )[0] #   1 < x <5

여러 조건을 만족시키는 경우 :

select_indices = np.where( np.logical_or( x < 1, x > 5 ) )[0] # x <1 or x >5

나는 np.vectorize그러한 작업 에 사용 하고 싶습니다 . 다음을 고려하세요:

>>> # Arrays
>>> x = np.array([5, 2, 3, 1, 4, 5])
>>> y = np.array(['f','o','o','b','a','r'])

>>> # Function containing the constraints
>>> func = np.vectorize(lambda t: t>1 and t<5)

>>> # Call function on x
>>> y[func(x)]
>>> array(['o', 'o', 'a'], dtype='<U1')

벡터화 된 함수에 더 많은 유형의 구속 조건을 추가 할 수 있다는 장점이 있습니다.

도움이 되길 바랍니다.


실제로 나는 이렇게 할 것입니다 :

L1은 조건 1을 만족하는 요소의 색인 목록입니다. ( L1을 사용 somelist.index(condition1)하거나 np.where(condition1)얻을 수 있습니다 .)

마찬가지로 조건 2를 만족하는 요소 목록 인 L2를 얻습니다.

그런 다음을 사용하여 교차점을 찾습니다 intersect(L1,L2).

여러 조건을 만족하는 경우 여러 목록의 교차를 찾을 수도 있습니다.

Then you can apply index in any other array, for example, x.


For 2D arrays, you can do this. Create a 2D mask using the condition. Typecast the condition mask to int or float, depending on the array, and multiply it with the original array.

In [8]: arr
Out[8]: 
array([[ 1.,  2.,  3.,  4.,  5.],
       [ 6.,  7.,  8.,  9., 10.]])

In [9]: arr*(arr % 2 == 0).astype(np.int) 
Out[9]: 
array([[ 0.,  2.,  0.,  4.,  0.],
       [ 6.,  0.,  8.,  0., 10.]])

참고URL : https://stackoverflow.com/questions/3030480/numpy-array-how-to-select-indices-satisfying-multiple-conditions

반응형