ndarray의 인덱싱과 슬라이싱

김상윤·2023년 2월 27일
0

벡터 ndarray의 인덱싱과 슬라이싱

ndarray의 인덱싱과 슬라이싱은 python의 list와 동일하게 작동한다.
[inclusive start:exclusive end]

import numpy as np

a = numpy.arange(10) [0 1 2 3 4 5 6 7 8 9]
a[5:-1] [5 6 7 8] 9 바로 전까지
a[2:] [2 3 4 5 6 7 8 9]
a[-2:] [8 9]
a[:5] [0 1 2 3 4]
a[:-3] [0 1 2 3 4 5 6] 7 바로 전까지
a[:] 전부다
a[::3] [0 3 6 9]
a[7:2:-1] [7 6 5 4 3] 2 나오기 전까지
a[::-1] reverse order

Element assignment with slicing
a[:5] = 0 [ 0 0 0 0 0 6 7 8 9]
a[::2] = 200 [200 1 200 3 200 5 200 7 200 9]

행렬 ndarray의 인덱싱과 슬라이싱

행렬 ndarray의 인덱싱이 python list와 차이가 나는 지점은 인덱싱 문법에 있다

import numpy as np
a = np.arange(9).reshape((3,3))
a[0,0], a[0,1], a[0,2] -> 0 1 2

,를 기준으로 인덱싱할 수 있다.

import numpy as np

a = np.arange(12).reshape((4,3))
a[1:,0] [3 6 9] 0번쨰 column의 1 2 3 index


Trick
이미지의 Flip
horizontal_flip = image[:,::-1]
vertical_flip = image[::-1,:]

0번째 이미지를 가져오세요
image[0,...]

3차원 ndarray의 인덱싱과 슬라이싱

다양한 인덱싱 결과 예시

a[:,:-1,:]

a[:,:,0]

a[1:,-2:,-2:]

image = np.random.normal(size = (3, 500, 300))
image_r = image[0]
image_g = image[1]
image_b = image[2]

import numpy as np

image = np.random.normal(size=(3,500,300))
top_left = image[:,:100,:100]
top_right = image[:,:100,-100:]
bottom_left = image[:,-100:,:100]
bottom_right = image[:,-100:,-100:]

int ndarray를 이용하여 인덱싱하기

규칙적이지 않은 인덱싱을 하고 싶을 때는 어떻게 해야할까?

import numpy as np
a = np.arange(10)
indice = np.array([0,3,4])
a[indice]	[0 3 4]

중복도 가능하다!

import numpy as np
a = np.arange(10)
indice = np.array([0,0,5,5])
a[indice]	[0 0 5 5]

Indice 자체를 특정 shape으로 만들어서 array를 생성할 수 있다
reshape 필요 없다

import numpy as np
a = np.arange(10)
indice = np.array([[1,2,3] [5,8,9]])
a[indice]	[[1 2 3]
			[5 8 9]]

Matrix를 인덱싱으로 접근할때

import numpy as np
a = np.arange(12).reshape((3,4))
indice = np.array([0,2]) (2,) shape의 array를 만들고 싶은 것
a[indice] -> [a[0],a[2]]

a[0] (4,) shape의 array가 (2,)에 각각 들어온다 -> (2,4)
import numpy as np
a = np.arange(12).reshape((3,4))
indice = np.array([0,0,1,1,2,2]) (6,) shape의 array를 만들고 싶은 것
a[indice] -> [a[0],a[0]...a[2]]

a[0] (4,) shape의 array가 (6,)에 각각 들어온다 -> (6,4)

2개의 차원에 대해서 인덱싱 하는법

import numpy as np
a = np.arange(12).reshape((3,4))
indice0, indice1 = np.array([0]), np.array([1])
a[indice0,indice1] [1]
import numpy as np
a = np.arange(12).reshape((3,4))
indices0, indices1 = np.array([0,1,2]), np.array([1,2,3])

for idx0, idx1 in zip(indices0, indices1):
	print(f"({idx0}, {idx1})")

(0,1)
(1,2)
(2,3)

a[indices0, indices1] [1 6 11]

boolean ndarray로 인덱싱하기

import numpy as np
a = np.arange(5)
b_indices = np.array([True, False, True, True, False])

a[b_indices] [0 2 3]

True 인덱스에 해당하는 값만 뽑아온다

c = np.random.randint(0,20,(10,))
b_indices = (a%2 == 0)
c[b_indices] 짝수 index만 뽑기
d = np.random.randint(0,20,(2,2))
b_indices = np.array([True, False],
					 [False, True]])
d[b_indices] [10, 19]

인덱싱하고 벡터를 출력한다

import numpy as np

a = np.array([[[True, False, True]
			   [True, False, False]],
               
              [[False, True, False]
               [True, False, True]]])

nonzero = np.nonzero(a)
(array([0,0,0,1,1,1]),
array([0,0,1,0,1,1]),
array([0,2,0,1,0,2]))

where = np.where(a)
(array([0,0,0,1,1,1]),
array([0,0,1,0,1,1]),
array([0,2,0,1,0,2]))
profile
AI 대학원 지망생

0개의 댓글