python/numpy
8. boolean indexing
Abokadoh
2023. 2. 16. 14:36
boolean indexing이란 ndarray인덱싱 시, bool 리스트를 전달하여 True인 경우에만 필터링하여 ndarray의 값을 반환받는 것을 말한다.
broadcasting을 활용하여 ndarray로부터 bool list를 얻고 짝수인 경우만을 뽑아보자.
# <in>
import numpy as np
np.random.seed(10)
x = np.random.randint(1, 100, size = 10)
print(x)
# <out>
[10 16 65 29 90 94 30 9 74 1]
원소가 10개인 1차원 벡터를 만들었다.
x에서 원소의 값이 짝수인 경우의 bool list를 만들어보자.
# <in>
np.random.seed(10)
x = np.random.randint(1, 100, size=10)
print(x)
x % 2 ==0
# <out>
[10 16 65 29 90 94 30 9 74 1]
array([ True, True, False, False, True, True, True, False, True,
False])
이 boolean list를 그대로 x에 인덱싱 해보자.
# <in>
np.random.seed(10)
x = np.random.randint(1, 100, size=10)
print(x)
x[x % 2 ==0]
# <out>
[10 16 65 29 90 94 30 9 74 1]
array([10, 16, 90, 94, 30, 74])
True인 인덱스만을 뽑아낸 것을 확인할 수 있다. 이렇게 만든 조건을 객체화해서 객체를 이용해 인덱싱하는 방법도 있다.
# <in>
np.random.seed(10)
x = np.random.randint(1, 100, size=10)
print(x)
even_mask = x % 2 ==0
x[even_mask]
# <out>
[10 16 65 29 90 94 30 9 74 1]
array([10, 16, 90, 94, 30, 74])
역시 같은 결과를 얻을 수 있다.
numpy의 ndarray에서의 필터링은 python list와 비교했을 때 이렇게 간단하다.
주의할 점은 파이썬 논리 연산자인 and, or, not 키워드를 사용할 수 없다는 것인데
and 대신 &, or 대신 |(shift + \)을 사용한다.
# <in>
np.random.seed(10)
x = np.random.randint(1, 100, size=10)
print(x)
x % 2 ==0
x < 30
x[(x % 2 ==0) & (x < 30) ]
# <out>
[10 16 65 29 90 94 30 9 74 1]
array([10, 16])
# <in>
np.random.seed(10)
x = np.random.randint(1, 100, size=10)
print(x)
x < 30
x > 50
x[(x < 30) | (x > 50)]
# <out>
[10 16 65 29 90 94 30 9 74 1]
array([10, 16, 65, 29, 90, 94, 9, 74, 1])
참 간단하다.