NumPy 검색

2021. 9. 11. 23:32·Programming/DIP
728x90
728x90

np.where

# np.where는 NumPy의 조건 기반 선택 함수
np.where(condition[, x, y])

 

Return elements chosen from x or y depending on condition.

  • condition : 검색에 사용될 조건.
    • 실제로 boolean array가 됨.
  • x : condition이 True에 해당하는 위치에 지정되는 값 또는 array (검색에 사용된 ndarray로 broadcast처리 가능한 shape이어야 함)
  • y : condition이 False에 해당하는 위치에 지정되는 값 또는 array (검색에 사용된 ndarray로 broadcast처리 가능한 shape이어야 함)

반환값

  • x,y를 설정해준 경우엔 조건에 따라 해당 값으로 채워진 ndarray임.
  • 아닌 경우, condition에 True에 해당하는 위치의 idx.
    • ndim 2인 ndarray가 condition에 사용된 경우, 2개의 ndarray를 가지는 tuple이 반환되고,
    • ndim 3인 ndarray의 경우에는 3개의 ndarray를 가지는 tuple임.

ref. NumPy API

 

numpy.where — NumPy v2.1 Manual

Return elements chosen from x or y depending on condition. Note When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses. The rest

numpy.org


Simple example

import numpy as np

a = np.arange(12).reshape(3,4)
x = np.array([
    [ 0, 1, 2, 3],
    [10,11,12,13],
    [20,21,22,23]
   ])
y = np.zeros((3,4))
print(np.where(a > 5,x,y))

위의 경우,

5이하 값을 가지는 위치는 0 (y가 모든 위치의 값이 0이므로) 의 값을 가지고,

5를 초과하는 위치는 x의 해당 위치의 값을 가지는 ndarray를 반환.

 

결과는 다음과 같음.

[[ 0.  0.  0.  0.]
 [ 0.  0. 12. 13.]
 [20. 21. 22. 23.]]

다음은 x,y를 지정하지 않은 경우의 예임.

import numpy as np

a = np.arange(12).reshape(3,4)
print(np.where(a > 5)

결과는 다음과 같음.

(array([1, 1, 2, 2, 2, 2]), array([2, 3, 0, 1, 2, 3]))
  • 첫번째 ndarray는 axis 0에서 condition이 True(참)인 위치들의 index임.
  • 두번째 ndarray는 axis 1에서 condition이 True(참)인 위치들의 index임.

numpy.where의 반환값으로 얻어진 index를 활용하여

  • 조건에 만족하는 위치는 1로
  • 아닌 위치는 0인
  • ndarray를 다음과 같이 얻을 수도 있다.

(보통은 x,y를 1, 0으로 지정하면 한번에 얻을 수 있음. 여기서는 index로 구성된 ndarray tuple을 어떻게 사용할 수 있는지를 확인하는 정도로 이해하면 될 듯 하다.)

import numpy as np
a = np.arange(12).reshape(-1,4)
coords = np.where( (a>3) & (a<8))
print(coords)
c = np.zeros_like(a) 
c[coords]=1
print(c)

 

위의 결과는 다음과 같다.

(array([1, 1, 1, 1]), array([0, 1, 2, 3]))
[[0 0 0 0]
 [1 1 1 1]
 [0 0 0 0]]

추가 : 반환된 idx ndarray들의 tuple의 좌표들을 요소로 갖는 ndarray만들기.

import numpy as np

a = np.array([
    [1,0,2],
    [3,0,0]])
coord_array = np.stack(np.where(a==0),axis=-1) 
coord_array

결과는 다음과 같음.

array([[0, 1],
       [1, 1],
       [1, 2]])
  • numpy.zeros등으로 초기화하고 값을 설정할 때 사용할 수 있는 형태는 아님.
  • 값 설정에 사용하려면, 각 axis별의 index를 따로 가지는 np.where에서 반환하는 형태를 사용해야함.

기타 검색용 function

  • numpy.nonzero(array) : Return the indices of the elements that are non-zero ( 행의 idx, 열의 idx를 가진 tuple).
  • numpy.isnan(array) : Test element-wise for NaN and return as a boolean array (=array와 같은 shape).
  • numpy.isinf(array) : Test element-wise for positive or negative infinity. Returns a boolean array of the same shape as x, True where x == +/-inf, otherwise False.

사실 numpy.where로 다 대체가 가능함.


같이보면 좋은 자료들

https://ds31x.tistory.com/344

 

[Summary] NumPy(Numerical Python)

파이썬 생태계에서 과학적 계산의 기본이 되는 라이브러리 NumPy는 파이썬에서 과학 계산과 수치 연산을 효율적으로 처리하기 위한 라이브러리 n-dimensional array(다차원 배열)인 ndarray 객체를 중심

ds31x.tistory.com

 

'Programming > DIP' 카테고리의 다른 글

PIL과 opencv에서의 image 변환.  (1) 2021.11.22
Conda backup for DIP 2021  (0) 2021.09.18
NumPy : sum, mean, std, and so on  (0) 2021.09.17
NumPy 배열 나누기: 영상 자르기 - split  (0) 2021.09.11
NumPy 배열 병합 : 영상 붙이기  (0) 2021.09.11
'Programming/DIP' 카테고리의 다른 글
  • Conda backup for DIP 2021
  • NumPy : sum, mean, std, and so on
  • NumPy 배열 나누기: 영상 자르기 - split
  • NumPy 배열 병합 : 영상 붙이기
dsaint31x
dsaint31x
    반응형
    250x250
  • dsaint31x
    Dsaint31's blog
    dsaint31x
  • 전체
    오늘
    어제
    • 분류 전체보기 (748)
      • Private Life (13)
      • Programming (56)
        • DIP (112)
        • ML (26)
      • Computer (119)
        • CE (53)
        • ETC (33)
        • CUDA (3)
        • Blog, Markdown, Latex (4)
        • Linux (9)
      • ... (351)
        • Signals and Systems (103)
        • Math (172)
        • Linear Algebra (33)
        • Physics (42)
        • 인성세미나 (1)
      • 정리필요. (54)
        • 의료기기의 이해 (6)
        • PET, MRI and so on. (1)
        • PET Study 2009 (1)
        • 방사선 장해방호 (4)
        • 방사선 생물학 (3)
        • 방사선 계측 (9)
        • 기타 방사능관련 (3)
        • 고시 (9)
        • 정리 (18)
      • RI (0)
      • 원자력,방사능 관련법 (2)
  • 블로그 메뉴

    • Math
    • Programming
    • SS
    • DIP
  • 링크

    • Convex Optimization For All
  • 공지사항

    • Test
    • PET Study 2009
    • 기타 방사능관련.
  • 인기 글

  • 태그

    SS
    Probability
    SIGNAL
    인허가제도
    signal_and_system
    fourier transform
    function
    opencv
    cv2
    Programming
    Python
    Term
    numpy
    Optimization
    signals_and_systems
    Vector
    math
    DIP
    linear algebra
    Convolution
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
dsaint31x
NumPy 검색
상단으로

티스토리툴바