배열 속성과 검사
ndim, shape, size, dtype 속성을 살펴보고 reshape()로 배열의 형태를 바꾸는 방법을 배웁니다.
배열 속성과 검사은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Pandas & NumPy Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Array Attributes Matter
Before working on an array, you'll want to know its shape, dimensions, and dtype. NumPy hands you these instantly through lightweight attributes.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print('ndim:', a.ndim) # 2
print('shape:', a.shape) # (2, 3)
print('size:', a.size) # 6
print('dtype:', a.dtype) # int64ndim: Number of Dimensions
ndim tells you how many dimensions an array has: a flat list is 1, a list of lists is 2, and ML tensors often go to 3 or 4.
import numpy as np
v = np.array([1, 2, 3])
print(v.ndim) # 1
m = np.zeros((4, 5))
print(m.ndim) # 2
t = np.ones((2, 3, 4))
print(t.ndim) # 3shape: The Dimension Tuple
shape is a tuple with one size per dimension. For a 2-D array, that's (rows, columns) — and you can unpack it to write flexible code.
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a.shape) # (2, 3, 4)
n_rows, n_cols = np.zeros((5, 7)).shape
print(n_rows, n_cols) # 5 7size: Total Number of Elements
size gives the total element count — every value in shape multiplied together. Handy for double-checking a reshape didn't lose anything.
import numpy as np
a = np.ones((3, 4, 5))
print(a.size) # 60 (3*4*5)
print(np.prod(a.shape))# 60
# Memory estimate in bytes
print(a.size * a.itemsize, 'bytes') # 480 bytesdtype: Element Data Type
The dtype describes each element's type, and itemsize tells you its byte size. Switching float64 to float32 halves memory and often runs faster.
import numpy as np
a = np.array([1.5, 2.5, 3.5])
print(a.dtype) # float64
print(a.itemsize) # 8 bytes
b = a.astype(np.float32)
print(b.dtype) # float32
print(b.itemsize) # 4 bytesnbytes: Total Memory Usage
nbytes is the array's total memory in bytes — just size times itemsize. Check it before and after downcasting to confirm you actually saved space.
import numpy as np
a = np.ones((1000, 1000), dtype=np.float64)
print(a.nbytes) # 8000000 (8 MB)
b = a.astype(np.float32)
print(b.nbytes) # 4000000 (4 MB)reshape(): Changing Array Shape
reshape gives the array a new shape without copying data, as long as the element count stays the same. Pass -1 and NumPy figures out that dimension for you.
import numpy as np
a = np.arange(12)
print(a.shape) # (12,)
b = a.reshape(3, 4)
print(b.shape) # (3, 4)
c = a.reshape(2, -1) # -1 inferred as 6
print(c.shape) # (2, 6)Flattening with ravel() and flatten()
Both ravel() and flatten() squash an array down to 1-D. The difference: ravel usually shares memory (no copy), while flatten always makes a fresh copy.
import numpy as np
m = np.array([[1, 2, 3], [4, 5, 6]])
r = m.ravel() # view (usually)
f = m.flatten() # always a copy
print(r) # [1 2 3 4 5 6]
print(f) # [1 2 3 4 5 6]Transposing Arrays
The .T attribute gives you the transpose — rows and columns swapped. It's free (no data copied) and essential for lining up matrices.
import numpy as np
m = np.array([[1, 2, 3], [4, 5, 6]]) # shape (2, 3)
print(m.T.shape) # (3, 2)
print(m.T)
# [[1 4]
# [2 5]
# [3 6]]strides: Memory Layout
strides show how many bytes NumPy steps through memory per dimension. This is why transposing is free — it just swaps the stride values.
import numpy as np
a = np.ones((3, 4), dtype=np.float64)
print(a.strides) # (32, 8) — 4 cols x 8 bytes, 1 col x 8 bytes
b = a.T
print(b.strides) # (8, 32) — strides swapped, no data copyChecking Views vs Copies
A view shares memory with the original, so changing one changes both; a copy is independent. Use np.shares_memory(a, b) to check which you have.
import numpy as np
a = np.arange(6)
b = a.reshape(2, 3) # view
print(np.shares_memory(a, b)) # True
c = a.copy()
print(np.shares_memory(a, c)) # FalseQuick Check
Test your understanding of NumPy array attributes from this lesson.
Lesson Recap
Great progress! ndim, shape, and size describe structure, dtype describes the data, and reshape returns a view while flatten always copies. Next: array math.
자주 묻는 질문
“배열 속성과 검사” 강의는 무료인가요?
네 — “배열 속성과 검사” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“배열 속성과 검사”에서 뭘 배우나요?
ndim, shape, size, dtype 속성을 살펴보고 reshape()로 배열의 형태를 바꾸는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“배열 속성과 검사” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- NumPy 배열 만들기
- 배열 속성과 검사
- 원소별 산술 연산
- 배열 슬라이싱과 인덱싱