블로그Python/NumPy

NumPy 3편: 모양 바꾸기와 합치기

NumPy 배열의 reshape, 전치, 펼치기, 축 추가와 순서 바꾸기(transpose), concatenate·stack·split을 예제와 실행 결과로 정리했다.

Python 3.14.8NumPy 2.5.4

이 글의 코드와 수치는 노트북으로 직접 실행해 볼 수 있다.

노트북 내려받기

NumPy 배열의 모양을 바꾸고, 축을 더하거나 순서를 바꾸고, 여러 배열을 합치고 나누는 방법을 정리했다. 예제의 출력은 모두 노트북을 실행한 결과다.

한눈에 보기

하고 싶은 것 코드 결과 / 주의
모양 바꾸기 x.reshape(3, 4), x.reshape(2, -1) 원소 개수는 그대로. -1은 한 번만
행과 열 바꾸기 m.T 1차원 배열에는 효과가 없다
1차원으로 펼치기 x.flatten(), x.ravel(), x.reshape(-1) flatten만 항상 복사본
축 추가와 제거 x[np.newaxis], x[:, None], np.squeeze(x) 크기 1인 축만 더하고 뺀다
축 순서 바꾸기 img.transpose(2, 0, 1), np.moveaxis(img, -1, 0) reshape로는 축 순서를 바꿀 수 없다
이어 붙이기와 쌓기 np.concatenate([a, b], axis=0), np.stack([a, b]) concatenate는 기존 축, stack은 새 축
나누기 np.split(x, 3), np.split(x, [2, 5]), np.array_split(x, 3) split은 똑같이 나누어떨어져야 한다

모양 바꾸기

reshape는 원소를 앞에서부터 차례로 새 모양에 채운다. 원소 개수는 바뀌지 않는다. 한 축을 -1로 두면 그 축의 크기를 NumPy가 계산한다.

python
a = np.arange(12)
print(a.reshape(3, 4))
print(a.reshape(2, -1))
print(a.reshape(-1, 1).shape)
출력
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]]
(12, 1)

reshape(-1, 1)은 1차원 배열을 열 하나짜리 행렬로 만든다. 2차원 배열을 요구하는 함수에 1차원 데이터를 넘길 때 쓴다.

python
for shape in [(5, -1), (-1, -1)]:
    try:
        a.reshape(shape)
    except ValueError as e:
        print('ValueError:', e)
출력
ValueError: cannot reshape array of size 12 into shape (5,newaxis)
ValueError: can only specify one unknown dimension

행과 열 바꾸기

.T는 행과 열을 바꾼다(전치). (2, 3)이 (3, 2)가 된다.

python
m = np.arange(6).reshape(2, 3)
print(m)
print(m.T)
print(m.shape, m.T.shape)

v = np.array([1, 2, 3])
print(v.shape, v.T.shape, v.reshape(-1, 1).shape)
출력
[[0 1 2]
 [3 4 5]]
[[0 3]
 [1 4]
 [2 5]]
(2, 3) (3, 2)
(3,) (3,) (3, 1)

1차원으로 펼치기

방법 결과
x.flatten() 항상 복사본
x.ravel(), x.reshape(-1) 가능하면 뷰(원본 메모리 공유), 안 되면 복사본

NumPy 문서도 ravel은 “가능하면” 뷰를, flatten은 “항상” 복사본을 돌려준다고 적는다(NumPy 문서: Copies and views).

python
m = np.arange(6).reshape(2, 3)
f = m.flatten()
f[0] = 99
r = m.ravel()
r[1] = 77
print(m)
print(np.shares_memory(m, f), np.shares_memory(m, r))
print(np.shares_memory(m, m.T), np.shares_memory(m, m.T.ravel()))
출력
[[ 0 77  2]
 [ 3  4  5]]
False True
True False

flatten 결과를 고친 것(99)은 원본에 반영되지 않았고, ravel 결과를 고친 것(77)은 반영되었다. 전치 m.T는 뷰지만, m.T.ravel()은 복사본이다. 전치된 배열은 메모리에 놓인 순서와 읽는 순서가 달라서 일렬로 펼치려면 복사해야 한다.

축 추가와 제거

크기가 1인 축을 더하거나 뺀다. 값은 그대로이고 shape만 바뀐다.

코드 (3,)에 적용한 결과
v[np.newaxis, :] (1, 3): 행 하나
v[:, np.newaxis], v[:, None] (3, 1): 열 하나
np.expand_dims(x, 축) 지정한 위치에 크기 1인 축 추가
np.squeeze(x), x.squeeze(axis=축) 크기 1인 축 제거
python
v = np.array([1, 2, 3])
print(v[np.newaxis, :].shape, v[:, np.newaxis].shape, v[:, None].shape)

img = np.zeros((28, 28))
batch = img[np.newaxis]
print(batch.shape, np.expand_dims(img, 0).shape)
print(np.squeeze(batch).shape, batch.squeeze(axis=0).shape)
출력
(1, 3) (3, 1) (3, 1)
(1, 28, 28) (1, 28, 28)
(28, 28) (28, 28)

(28, 28) 배열 앞에 축을 더하면 (1, 28, 28), 즉 “1장짜리 묶음”이 된다. 여러 장을 묶은 배열과 모양을 맞출 때 쓴다.

축 순서 바꾸기

컬러 이미지는 3차원 배열인데, 채널 축을 맨 뒤에 두는 (세로, 가로, 채널)과 맨 앞에 두는 (채널, 세로, 가로)가 모두 쓰인다. 한쪽에서 다른 쪽으로 바꾸려면 축 순서를 바꾼다.

코드 결과
x.transpose(2, 0, 1) 새 순서의 각 자리에 올 원래 축 번호를 적는다. (H, W, C) → (C, H, W)
np.moveaxis(x, -1, 0) 축 하나를 옮긴다. 마지막 축을 맨 앞으로
python
img = np.arange(4 * 6 * 3).reshape(4, 6, 3)  # (세로, 가로, 채널)
chw = img.transpose(2, 0, 1)                  # (채널, 세로, 가로)
print(chw.shape, np.moveaxis(img, -1, 0).shape)
print(chw[np.newaxis].shape)
print(np.array_equal(chw[0], img[:, :, 0]))
print(np.shares_memory(img, chw))
출력
(3, 4, 6) (3, 4, 6)
(1, 3, 4, 6)
True
True

chw[0]은 원래 이미지의 0번 채널 img[:, :, 0]과 같다. transpose 결과는 복사하지 않은 뷰다. 맨 앞에 축을 하나 더하면 (1, 3, 4, 6)이 된다.

python
wrong = img.reshape(3, 4, 6)
print(wrong.shape)
print(np.array_equal(wrong[0], img[:, :, 0]))
print(img[0, :, 0])   # 빨강 채널의 첫 행
print(chw[0, 0])
print(wrong[0, 0])
출력
(3, 4, 6)
False
[ 0  3  6  9 12 15]
[ 0  3  6  9 12 15]
[0 1 2 3 4 5]

빨강 채널의 첫 행은 [0 3 6 …]이어야 한다. transpose 결과는 맞지만, reshape 결과 [0 1 2 …]는 첫 픽셀의 빨강·초록·파랑과 다음 픽셀의 값이 섞인 것이다. shape만 봐서는 구별되지 않는다.

이어 붙이기와 쌓기

함수 하는 일 (2, 2) 두 개의 결과
np.concatenate([a, b], axis=0) 기존 0번 축(행)을 따라 잇는다. np.vstack과 같다 (4, 2)
np.concatenate([a, b], axis=1) 기존 1번 축(열)을 따라 잇는다. np.hstack과 같다 (2, 4)
np.stack([a, b]) 새 축을 맨 앞에 만들어 쌓는다 (2, 2, 2)
python
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print(np.concatenate([a, b], axis=0))
print(np.concatenate([a, b], axis=1))
print(np.vstack([a, b]).shape, np.hstack([a, b]).shape)
print(np.stack([a, b]).shape)
출력
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
[[1 2 5 6]
 [3 4 7 8]]
(4, 2) (2, 4)
(2, 2, 2)
python
imgs = [np.zeros((28, 28)) for _ in range(100)]
print(np.stack(imgs).shape)
print(np.concatenate(imgs).shape)
출력
(100, 28, 28)
(2800, 28)

나누기

함수 하는 일
np.split(x, n) n등분. 나누어떨어지지 않으면 에러
np.split(x, [i, j]) i번, j번 앞에서 자른다
np.array_split(x, n) n조각. 나누어떨어지지 않으면 앞 조각이 하나씩 더 길다
python
x = np.arange(12)
print(np.split(x, 3))
print(np.split(x, [2, 5]))
try:
    np.split(np.arange(10), 3)
except ValueError as e:
    print('ValueError:', e)
print(np.array_split(np.arange(10), 3))
출력
[array([0, 1, 2, 3]), array([4, 5, 6, 7]), array([ 8,  9, 10, 11])]
[array([0, 1]), array([2, 3, 4]), array([ 5,  6,  7,  8,  9, 10, 11])]
ValueError: array split does not result in an equal division
[array([0, 1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])]

np.split(x, [2, 5])는 x[:2], x[2:5], x[5:]로 나눈다.