딥러닝·머신러닝/Python

Python Numpy Basic 3 (Broadcasting, Boolean Indexing)

경이가 꿈꾸는 플랫폼 개발 2021. 10. 31. 09:42

1. BroadCasting

 

(기본적으로)Shape이 같은 두 ndarray에 대한 연산은 각 원소별로 진행

다른 Shape을 갖는 array 간 연산 의 경우 브로드 캐스팅(Shape을 맞춤) 후 진행

가장 마지막 차원 ( a X b X c ) 에서 c 와 일치하는 길이의 Array와 함께 연산할 수 있음

arr1 = np.arange(10, 70, 10).reshape(2, 3)
arr2 = np.array([1, 2])  # (2,)
arr1 = arr1.reshape(3,2)
arr1 = arr1 + arr2
arr1.reshape(2,3)

# array([[11, 22, 31],
#        [42, 51, 62]])

 

2. Boolean Indexing

 

True만 걸러서 Indexing하는 것

ndarry indexing할 때, bool 리스트를 전달하여 True인 경우만 필터링

x = np.random.randint(1, 100, size=10)
x_filter = x % 2 == 0 

for n, b in zip(x, even_mask):
    print(n, b, end=", ")

x[x_filter]

# array([14, 10, 44, 18, 86, 96, 79, 19, 91,  4])
# array([ True,  True,  True,  True,  True,  True, False, False, False, True])
# 14 True, 10 True, 44 True, 18 True, 86 True, 96 True, 79 False, 19 False, 91 False, 4 True, 
# array([14, 10, 44, 18, 86, 96,  4])

x[x % 2 == 0]

# array([14, 10, 44, 18, 86, 96,  4])

& ← AND, | ← OR, 비교연산자 chaining 불가 (원래는 x[30 < x < 50] 가능하지만 Boolean Indexing 시 안됨)

x[((x % 2) == 0) & (x < 30)]
x[((x % 2) == 0) | (x < 30)] 

# array([14, 10, 18,  4])
# array([44])

 

True, False로 이루어진 Array를 astype(int)로 변환해서 1, 0으로 바꿔서 만들어줄 수 있음

(x>50).astype(int)

# array([0, 0, 0, 0, 1, 1, 1, 0, 1, 0])