Skip to content

NumPy 치트시트

파이썬 수치 계산의 기초가 되는 패키지입니다.

01

시작하기

NumPy란?

NumPy의 힘은 ndarray에서 나옵니다. 동질적(homogeneous)이고 연속 메모리에 담긴 n차원 배열입니다. 모든 요소가 하나의 타입을 공유하고 하나의 블록에 있으므로 연산이 컴파일된 C/Fortran 코드에서 실행됩니다(벡터화). 등가의 Python 루프보다 10~100배 빠릅니다. 거의 모든 과학 파이썬 스택(pandas, scikit-learn, PyTorch, TensorFlow)이 NumPy 배열 위에 세워져 있습니다.

numpy
# NumPy: the fundamental package for numerical computing in Python.
# Core data structure: the n-dimensional array (ndarray).

# Key advantages over pure Python lists:
# - Homogeneous, contiguous memory -> fast vectorized ops
# - Broadcasting: operate on arrays of different shapes
# - Rich set of math / linear algebra / FFT / random routines
# - C/Fortran backend -> orders of magnitude faster than Python loops

import numpy as np
print(np.__version__)   # e.g. 1.26.0

설치와 임포트

np가 NumPy의 사실상 표준 별칭입니다. 모든 튜토리얼과 라이브러리가 이를 기대하므로 그대로 유지하세요. CPU 최적화 빌드가 필요하면 conda가 MKL 링크 NumPy를 제공하는 경우가 많으며, 선형 대수에서 pip 기본보다 빠릅니다.

numpy
# Install NumPy
pip install numpy
# Or with conda
conda install numpy

# The universal convention is to alias as np
import numpy as np

a = np.array([1, 2, 3])
print(a)            # [1 2 3]
print(type(a))      # <class 'numpy.ndarray'>

ndarray 속성

이 속성들을 아는 것이 NumPy 코드 디버깅의 기초입니다. 가장 흔한 것은 shape과 dtype입니다. shape은 구조를, dtype은 메모리 점유를 알려 줍니다. itemsize * size = nbytes로 거대 배열 할당 전 메모리 사용량을 추정할 수 있습니다.

numpy
import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int64)

a.ndim      # 2          -> number of axes (dimensions)
a.shape     # (2, 3)     -> tuple of axis sizes
a.size      # 6          -> total elements = prod(shape)
a.dtype     # int64      -> element type
a.itemsize  # 8          -> bytes per element
a.nbytes    # 48         -> total bytes = size * itemsize
a.T         # shape (3, 2) transposed view
a.flat      # flat iterator over all elements

데이터 타입 (dtype)

올바른 dtype 선택은 메모리와 정확성에 결정적입니다. float32는 대부분의 ML 작업에서 정확도 손실이 거의 없이 float64 대비 메모리를 절반으로 줄입니다. int8/int16은 조용히 오버플로할 수 있습니다. np.array([200], dtype=np.int8)은 -56이 됩니다. 범위를 안전하게 담는 가장 작은 dtype을 고르세요. 특히 큰 배열과 임베디드/엣지 배포에서.

numpy
import numpy as np

# Specifying dtype at creation
a = np.array([1, 2, 3], dtype=np.float32)
b = np.array([1, 2, 3], dtype="float32")   # string form works too

# Integer types: int8 int16 int32 int64 (and unsigned uint*)
# Float types:   float16 float32 float64 (default)
# Complex:       complex64 complex128
# Others:        bool, string_, unicode_, object

# Cast an existing array
c = a.astype(np.int32)

# Default int/float match the platform
print(np.dtype(int).itemsize)        # 4 or 8
print(np.dtype(float).itemsize)      # 8

# Beware overflow:
small = np.array([200], dtype=np.int8)   # wraps around!

배열 vs Python 리스트

리스트 컴프리헨션 버전은 Python 인터프리터에서 실행됩니다(요소마다 바이트코드 하나). NumPy 버전은 연속 메모리 위의 단일 C 루프로 디스패치합니다. 수치 워크로드에서 NumPy는 보통 20~100배 빠르고 메모리도 훨씬 적게 씁니다(요소별 Python 객체 없음). 리스트는 이질적 타입이나 비수치 데이터가 필요할 때만 쓰세요.

numpy
import numpy as np
import time

# Python list: element-wise multiply needs a loop or comprehension
py_list = list(range(1_000_000))
start = time.perf_counter()
py_sq = [x * 2 for x in py_list]
print("list:", time.perf_counter() - start)

# NumPy: vectorized, runs in C
arr = np.arange(1_000_000)
start = time.perf_counter()
np_sq = arr * 2
print("numpy:", time.perf_counter() - start)

# NumPy is typically 20-100x faster for numeric workloads.
# Lists are heterogeneous & flexible; arrays are homogeneous & fast.
02

배열 생성

Python 구조에서 생성

np.array()가 리스트/튜플(또는 임의 중첩 이터러블)을 ndarray로 변환합니다. 중첩 깊이가 차원 수를 결정합니다. 이후 여분의 복사를 피하려 생성 시 dtype을 지정하세요. np.array([1,2,3])은 대부분 플랫폼에서 int64가 기본이므로 실수를 원하면 dtype=float을 전달하세요.

numpy
import numpy as np

# From a list (1-D)
a = np.array([1, 2, 3])

# From a list of lists (2-D)
b = np.array([[1, 2, 3],
              [4, 5, 6]])

# From nested lists (3-D)
c = np.array([[[1, 2], [3, 4]],
              [[5, 6], [7, 8]]])

# Specify dtype up front
d = np.array([1, 2, 3], dtype=np.float32)

# From any iterable
e = np.array(range(5))         # [0 1 2 3 4]
f = np.array((1, 2, 3))        # from a tuple

내장 범위와 격자

실수에는 arange보다 linspace를 선호하세요. arange의 step은 부동소수점 반올림으로 경계가 어긋날 수 있습니다. meshgrid는 3D 플로팅, 이미지 처리, 유한차분 계산의 좌표 격자를 만드는 표준 방법입니다. 개방형(메모리 절약) 격자에는 np.mgrid / np.ogrid를 쓰세요.

numpy
import numpy as np

# arange: like range but returns array (watch float edge!)
np.arange(0, 10, 2)         # [0 2 4 6 8]
np.arange(0, 1, 0.1)        # may or may not include 1.0 (float!)

# linspace: exactly num points, endpoints included by default
np.linspace(0, 1, 5)        # [0.   0.25 0.5  0.75 1.  ]

# logspace: 10**start .. 10**stop
np.logspace(0, 3, 4)        # [   1.   10.  100. 1000.]

# Meshgrids for evaluating functions on a grid
x = np.linspace(-2, 2, 5)
y = np.linspace(-2, 2, 5)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2             # 5x5 grid of values

Zeros, Ones, 상수

zeros/ones/full이 버퍼를 미리 채우고, empty는 채우기를 건너뛰어 어차피 모든 요소를 덮어쓸 때(예: 출력 버퍼) 가장 빠릅니다. eye(k=n)은 단위 행렬을 만들고, eye(k=1)은 대각선을 위로 이동시킵니다. zeros/ones에는 항상 dtype을 전달하세요. 기본은 float64로 정수를 원하면 메모리를 낭비합니다.

numpy
import numpy as np

np.zeros((2, 3))            # 2x3 of float64 zeros
np.zeros((2, 3), dtype=int) # 2x3 of int zeros
np.ones((3, 3))             # 3x3 of ones
np.full((2, 2), 7)          # 2x2 filled with 7
np.full((2, 2), np.pi)      # fill with any constant

# Identity & eye
np.eye(3)                   # 3x3 identity matrix
np.eye(3, k=1)              # identity shifted up by one diagonal
np.diag([1, 2, 3])          # diagonal matrix from a vector

# Empty: uninitialized memory (fastest, but garbage values)
np.empty((2, 2))            # allocate without filling

랜덤 배열

np.random.default_rng(seed)를 쓰세요. 현대 Generator가 더 빠르고, 통계적으로 더 좋고, 재현 가능합니다. 레거시 np.random.rand/randn/seed API는 전역 상태를 가지며 새 코드에서는 권장되지 않습니다. 실험과 테스트의 재현성을 위해 항상 명시적 seed를 전달하세요. 없으면 실행마다 결과가 달라집니다.

numpy
import numpy as np

rng = np.random.default_rng(seed=42)   # modern Generator (NumPy >= 1.17)

rng.random((2, 3))           # uniform in [0, 1), shape (2, 3)
rng.standard_normal((2, 3))  # standard normal (mean 0, std 1)
rng.normal(100, 15, size=5)  # normal(mu=100, sigma=15)
rng.uniform(0, 10, size=5)   # uniform in [low, high)
rng.integers(0, 10, size=5)  # random ints in [low, high)

# Reproducibility: always pass a seed
rng2 = np.random.default_rng(42)
print(rng2.random(3))        # same every run

# Legacy API (still common but prefer default_rng)
# np.random.rand(2, 3)      # uniform [0,1)
# np.random.randn(2, 3)     # standard normal

기존 배열 복사

슬라이싱과 .view()는 메모리를 공유하는 뷰를 만듭니다. 하나를 수정하면 다른 것도 바뀝니다. 독립 배열이 필요하면 .copy()를 쓰세요. reshape, ravel, transpose도 가능하면 뷰를 반환하므로 원본이 필요하면 수정 전에 항상 .copy()하세요. 이를 잊는 것이 가장 흔한 NumPy 버그 중 하나입니다.

numpy
import numpy as np
a = np.array([1, 2, 3])

# View (shares memory!) - shape change only
v = a.view()
v[0] = 99
print(a)   # [99  2  3]   <- a is mutated!

# Deep copy (independent)
b = a.copy()
b[0] = 0
print(a)   # [99  2  3]   <- a unchanged

# np.array defaults to copying
c = np.array(a)
c is a    # False

# Repeat / tile to expand arrays
np.repeat([1, 2, 3], 2)   # [1 1 2 2 3 3]
np.tile([1, 2, 3], 2)     # [1 2 3 1 2 3]
03

인덱싱과 슬라이싱

기본 슬라이싱

슬라이싱은 stop을 제외하는 Python의 [start:stop:step] 관례를 따릅니다. 결정적으로 NumPy 슬라이스는 뷰이며 원본과 메모리를 공유하므로, 슬라이스 수정이 원본을 바꿉니다. 의도된 동작이지만(메모리 절약) 빈번한 버그의 원천입니다. 독립 배열이 필요하면 .copy()를 쓰세요.

numpy
import numpy as np
a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

a[0]          # 0      (scalar)
a[-1]         # 9      (last element)
a[2:5]        # [2 3 4]    start:stop (stop excluded)
a[:5]         # [0 1 2 3 4]
a[5:]         # [5 6 7 8 9]
a[::2]        # [0 2 4 6 8]   step=2
a[::-1]       # [9 8 7 6 5 4 3 2 1 0]  reversed
a[1:7:2]      # [1 3 5]       start:stop:step

# Slices return VIEWS (not copies) -> editing changes the original
b = a[2:5]
b[0] = 99
print(a[2])   # 99   <- a was modified!

다차원 인덱싱

a[i][j]보다 a[i, j]를 쓰세요. 콤마 형태가 하나의 연산이며 더 빠릅니다. a[:, j]는 열 전체를 고릅니다. 3차원 이상 배열 작업 시 ... (Ellipsis)로 '나머지 모든 축'을 뜻하게 하여 여러 콜론을 쓰는 것을 피하세요. 각 슬라이스는 뷰를 반환합니다.

numpy
import numpy as np
a = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

a[1, 2]       # 6      (row 1, col 2) - equivalent to a[1][2] but faster
a[0]          # [1 2 3]   (row 0)
a[0, :]       # [1 2 3]   (row 0, all cols)
a[:, 1]       # [2 5 8]   (all rows, col 1)
a[1:3, 0:2]   # [[4 5]
              #  [7 8]]     rows 1-2, cols 0-1
a[-1]         # [7 8 9]    last row
a[:, -1]      # [3 6 9]    last column

# ... (ellipsis) selects any remaining full axes
b = np.zeros((2, 3, 4))
b[..., 0]     # shape (2, 3) - last axis indexed, others kept
b[1, ...]     # shape (3, 4) - first axis indexed

불리언 / 마스크 인덱싱

불리언 인덱싱은 항상 복사본을 반환하며 뷰가 아닙니다. 자유롭게 수정해도 안전합니다. 마스크 결합에는 & | ~를 쓰세요(and/or가 아님. 이들은 배열의 진리값에 대해 동작하며 오류를 냅니다). np.where은 인덱스를 반환하고, np.where(cond, x, y)는 벡터화된 삼항식입니다. 필터링과 조건 로직의 주력입니다.

numpy
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6])

# Build a boolean mask
mask = a > 3
# [False False False  True  True  True]

a[mask]            # [4 5 6]   (select elements where mask is True)
a[a > 3]           # same, in one expression
a[(a > 2) & (a < 6)]   # [3 4 5]   combine with & (and), | (or), ~ (not)

# Modify via mask
a[a > 3] = 0       # set all matching elements
a[a == 0] = -1     # conditional assignment

# Count matching elements
(a > 3).sum()      # 3   (True == 1)
np.count_nonzero(a > 3)

# np.where: positions where condition is True
np.where(a > 3)    # (array([3, 4, 5]),) indices

Fancy / 정수 배열 인덱싱

fancy(정수 배열) 인덱싱도 항상 복사본을 반환하며 뷰가 아닙니다. 두 인덱스 배열로 2차원 배열을 인덱싱하면 b[rows, cols]의 배열은 요소별로 짝지어집니다(점을 만듦). 곱집합(cross product)이 아닙니다. 곱집합은 np.ix_(rows, cols)를 쓰세요. 이 구분은 흔한 혼란의 원천입니다.

numpy
import numpy as np
a = np.array([10, 20, 30, 40, 50])

# Index with a list/array of indices
a[[0, 2, 4]]         # [10 30 50]
a[np.array([0, 2, 4])]   # same

# Indices can repeat
a[[0, 0, 1]]         # [10 10 20]

# Negative indices work
a[[-1, -2]]          # [50 40]

# 2-D fancy indexing
b = np.arange(12).reshape(3, 4)
rows = np.array([0, 2])
cols = np.array([1, 3])
b[rows, cols]        # [1 11]   pairs (0,1) and (2,3)

# Mix a slice and an index array
b[1:, [0, 2]]        # rows 1-2, cols 0 and 2

# np.take: same as fancy indexing, more flexible
np.take(a, [0, 2])   # [10 30]

인덱스 할당과 np.where

np.where(cond, x, y)는 벡터화된 if-else로 조건 기반 배열 생성에 극히 흔합니다. 인자 하나로는 조건이 True인 인덱스를 반환합니다. 여러 상호배타적 조건은 np.select가 처리하고, np.clip은 명시적 마스크를 쓰지 않고 값을 경계에 묶는 깔끔한 방법입니다.

numpy
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6])

# Conditional assignment with a mask
a[a % 2 == 0] = -1     # even -> -1: [1 -1 3 -1 5 -1]

# np.where(cond, x, y): vectorized ternary
b = np.where(a > 3, "big", "small")
# ['small' 'small' 'small' 'big' 'big' 'big']

# np.where with one argument -> indices of True
idx = np.where(a == -1)
# (array([1, 3, 5]),)

# np.select: multiple conditions, multiple choices
conds = [a < 3, a > 3, a == 3]
choices = ["low", "high", "mid"]
np.select(conds, choices, default="ok")

# np.clip: clamp values to a range
np.clip(a, 0, 4)       # values < 0 -> 0, > 4 -> 4
04

리셰이핑과 형상 조작

reshape과 -1 추론

reshape은 형상만 바꾸고 총 크기는 유지합니다. 한 차원에 -1을 쓰면 NumPy가 크기에서 추론하며 -1은 하나만 허용됩니다. reshape은 보통 뷰를 반환하므로(데이터 복사 없음) reshape된 배열 수정이 원본을 바꿉니다. 요소 총수는 유지되어야 하며 아니면 ValueError가 납니다.

numpy
import numpy as np
a = np.arange(12)        # [0 1 2 ... 11], shape (12,)

# reshape to (3, 4)
b = a.reshape(3, 4)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

# Use -1 to infer one dimension
a.reshape(2, -1)         # (2, 6)  - -1 means "figure it out"
a.reshape(-1, 3)         # (4, 3)
a.reshape(2, -1, 2)      # (2, 3, 2)  only one -1 allowed

# Total size must match -> ValueError otherwise
# a.reshape(5, 3)        # 5*3 = 15 != 12

# reshape returns a view when possible (no copy)
b[0, 0] = 99
print(a[0])              # 99   <- a was modified

Flatten과 Ravel

ravel()은 뷰를 반환하고(빠름, 메모리 공유) flatten()은 항상 복사본을 반환합니다(안전하지만 느리고 메모리 2배). 단순 순회는 ravel, 원본에 영향 없이 결과를 수정할 것은 flatten을 쓰세요. Fortran 코드나 MATLAB과 상호운용할 때는 order 인자가 중요합니다.

numpy
import numpy as np
a = np.array([[1, 2, 3],
              [4, 5, 6]])

# ravel: returns a VIEW (C order by default) - efficient
a.ravel()              # [1 2 3 4 5 6]
a.ravel(order='F')     # [1 4 2 5 3 6]   Fortran (column) order

# flatten: always returns a COPY - safe to mutate
flat = a.flatten()
flat[0] = 99
print(a[0, 0])         # 1   <- a unchanged

# Order conventions:
# 'C' (default): last axis varies fastest (row-major)
# 'F':           first axis varies fastest (column-major)
# 'A':           Fortran order if array is F-contiguous, else C
# 'K':           preserve memory order

Transpose와 축 교환

Transpose는 메모리 읽는 방식을 재정렬하는 뷰일 뿐이며 데이터를 복사하지 않습니다. 저렴하지만 결과가 연속적이지 않을 수 있습니다. 2차원에는 .T로 충분하고, 3차원 이상에서는 transpose(axis_order), swapaxes, moveaxis로 어느 축이 어디로 갈지 정확히 제어하세요. 비연속 배열 연산은 느릴 수 있으니 핫 루프에서는 np.ascontiguousarray가 도움이 됩니다.

numpy
import numpy as np
a = np.arange(12).reshape(3, 4)

a.T                 # shape (4, 3)   transpose (2-D)
a.transpose()       # same

# For 3+ dimensions, specify axis order
b = np.arange(24).reshape(2, 3, 4)
b.transpose(1, 0, 2)   # shape (3, 2, 4)  axes reordered
b.swapaxes(0, 1)       # shape (3, 2, 4)  swap two axes
b.T                   # shape (4, 3, 2)  reverse all axes

# Move axes to new positions
np.moveaxis(b, 0, -1)  # shape (3, 4, 2)

# All of these return VIEWS (no data copy)

배열 쌓기

stack은 새 축을 더하고(두 1차원 배열을 2차원으로) concatenate는 기존 축을 따라 이어붙입니다. vstack/hstack/dstack은 1차원과 2차원 배열의 편의 래퍼입니다. 복잡한 배치는 np.block이 서브 블록으로 행렬을 만들듯 배열의 중첩 리스트를 받습니다. 모든 쌓기 함수는 새 배열(복사본)을 만듭니다.

numpy
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

# Stack along a NEW axis
np.stack([a, b])            # shape (2, 3)  - default axis=0
np.stack([a, b], axis=1)    # shape (3, 2)  column stack

# Concatenate along an EXISTING axis
np.concatenate([a, b])              # [1 2 3 4 5 6]
np.vstack([a, b])                  # shape (2, 3)  vertical
np.hstack([a, b])                  # [1 2 3 4 5 6] horizontal
np.dstack([a, b])                  # shape (1, 3, 2) depth

# 2-D arrays
A = np.ones((2, 2))
B = np.zeros((2, 2))
np.hstack([A, B])   # shape (2, 4)
np.vstack([A, B])   # shape (4, 2)

# np.block: build from nested blocks
np.block([[A, B], [B, A]])   # shape (4, 4)

배열 분할

split은 같은 크기 청크가 필요하며(아니면 ValueError) array_split은 고르지 않은 나눗셈을 허용합니다. N이 나누어 떨어지지 않을 때 편리합니다. vsplit/hsplit/dsplit은 np.split(arr, n, axis=...)과 등가인 축별 헬퍼입니다. 모두 원본 배열에 대한 뷰의 리스트를 반환하므로 메모리 효율적입니다.

numpy
import numpy as np
a = np.arange(12)

# Split into equal parts (must divide evenly)
np.split(a, 3)        # [array([0,1,2,3]), array([4,5,6,7]), array([8,9,10,11])]

# Split at specific indices
np.split(a, [3, 5])   # [array([0,1,2]), array([3,4]), array([5,6,7,8,9,10,11])]

# 2-D
b = np.arange(16).reshape(4, 4)
np.vsplit(b, 2)       # split along rows -> 2 arrays of shape (2, 4)
np.hsplit(b, 2)       # split along cols -> 2 arrays of shape (4, 2)

# array_split: allows uneven division
np.array_split(np.arange(10), 3)  # sizes [4, 3, 3] - no error

# dsplit: split along depth (axis 2)
c = np.arange(24).reshape(2, 2, 6)
np.dsplit(c, 3)       # 3 arrays of shape (2, 2, 2)
05

Broadcasting

Broadcasting 규칙

Broadcasting은 크기 1의 축을 가상으로 확장해 다른 형상의 배열을 결합하게 합니다. 데이터는 실제 복사되지 않습니다. 규칙: 형상을 오른쪽부터 비교하며 각 축은 같거나 둘 중 하나가 1(또는 없음)이어야 합니다. 이것이 NumPy 코드를 간결하게 하지만(명시 루프 없음) 조용한 형상 버그의 흔한 원천이기도 합니다. 뭔가 이상하면 항상 형상을 확인하세요.

numpy
import numpy as np

# Broadcasting: operate on arrays of different shapes without copying.
# Two shapes are compatible if, for each trailing axis, they are
# equal OR one of them is 1.

# Scalar broadcast to any array
a = np.array([1, 2, 3])
a + 10            # [11 12 13]   10 treated as shape ()

# 1-D with 2-D
A = np.ones((3, 4))
row = np.array([10, 20, 30, 40])
A + row           # row (4,) broadcast to (3, 4) -> added to each row

col = np.array([[100], [200], [300]])   # shape (3, 1)
A + col           # col broadcast across columns -> added to each column

# Incompatible shapes raise ValueError
# A + np.array([1, 2, 3])   # (3,4) vs (3,) -> error

Broadcasting을 위한 축 추가

np.newaxis(별칭 None)가 크기 1의 축을 삽입합니다. 배열을 원하는 방식으로 broadcasting하도록 형상을 바꾸는 표준 트릭입니다. 열 축(a[:, None])과 행 축(a[None, :]) 추가로 외적, 쌍별 차이 등을 루프 없이 계산할 수 있습니다. 가독성을 위한 명명 함수 등가물은 np.expand_dims입니다.

numpy
import numpy as np
a = np.array([1, 2, 3])          # shape (3,)
b = np.array([10, 20, 30, 40])   # shape (4,)

# a + b would fail (3,) vs (4,)
# Insert a new axis so shapes become (3, 1) and (4,) -> broadcasts to (3, 4)

a_col = a[:, np.newaxis]   # shape (3, 1)  - same as a.reshape(-1, 1)
b_row = b[np.newaxis, :]   # shape (1, 4)

outer = a_col + b_row      # shape (3, 4)  outer sum
# [[11 21 31 41]
#  [12 22 32 42]
#  [13 23 33 43]]

# np.newaxis / None are equivalent
a[:, None]                 # same as a[:, np.newaxis]

# np.expand_dims is the explicit function form
np.expand_dims(a, axis=1)  # shape (3, 1)

외적과 쌍별 연산

새 축을 추가해 1차원 연산을 2차원 외적형 계산으로 바꾸는 것이 벡터화 NumPy의 핵심 관용구입니다. a[:, None] - b[None, :]가 루프 없이 모든 쌍별 차이를 계산하며 중첩 Python 루프보다 훨씬 빠릅니다. 이 패턴이 거리 행렬, 커널 계산, 격자 연산을 구동합니다.

numpy
import numpy as np
a = np.array([1, 2, 3])
b = np.array([10, 20, 30, 40])

# Outer product (3,) x (4,) -> (3, 4)
np.outer(a, b)
# [[10 20 30 40]
#  [20 40 60 80]
#  [30 60 90 120]]

# Manual outer via broadcasting
a[:, None] * b[None, :]      # same as np.outer(a, b)

# Pairwise difference: (4,) - (3,) -> (4, 3) or (3, 4)?
diff = b[:, None] - a[None, :]   # shape (4, 3): diff[i, j] = b[i] - a[j]

# Pairwise equality (used in set ops, distance)
x = np.array([1, 2, 3, 4])
y = np.array([2, 4, 6])
x[:, None] == y[None, :]     # shape (4, 3) boolean matrix

# Add a constant vector to each row of a matrix
M = np.zeros((5, 3))
v = np.array([1, 2, 3])
M + v                        # broadcasts v to every row

흔한 Broadcasting 함정

형상 (N,)의 1차원 배열은 2차원 배열에 대해 '행'으로 broadcasting됩니다. 열 벡터가 아닙니다. 열로 만들려면 축을 더해야 합니다: a[:, None]. 새 축 추가 시 의도치 않은 broadcasting에 주의하세요. 두 (1000, 1000) 배열이 (1000, 1000, 1000) 중간 결과(8GB)로 폭발해 프로그램을 크래시할 수 있습니다. 큰 계산 전에 .shape으로 항상 형상을 검증하세요.

numpy
import numpy as np

# Pitfall 1: (N,) is NOT a row or column vector - it has no axis direction
a = np.array([1, 2, 3])
M = np.ones((3, 3))
M + a            # OK: (3,3) + (3,) -> a broadcast as a ROW
M + a[:, None]   # OK: a as a COLUMN

# Pitfall 2: accidentally broadcasting when you wanted element-wise
x = np.array([1, 2, 3])
y = np.array([10, 20, 30])
x + y            # [11 22 33]   element-wise (both (3,))
x[:, None] + y   # (3,3) matrix  - probably not what you wanted!

# Pitfall 3: shape (1,) vs () - both broadcast but mean different things
np.array([5]).shape   # (1,)
np.array(5).shape     # ()  - 0-D, broadcasts to ANYTHING

# Pitfall 4: memory blow-up from over-broadcasting
# Big arrays broadcast together can produce enormous intermediates
A = np.ones((1000, 1000))
B = np.ones((1000, 1000))
(A * B).sum()    # OK - intermediate is 8MB
# A[:, None, :] * B[None, :, :]   # (1000,1000,1000) = 8GB! crash

np.broadcast_to를 곁들인 Broadcasting

np.broadcast_to는 broadcast된 뷰를 명시적으로 만듭니다. API가 특정 형상을 요구하지만 전체 복사의 메모리 비용을 피하고 싶을 때 유용합니다. 기저 데이터가 형상이 암시하는 것보다 작으므로 결과는 읽기 전용입니다. 여러 배열이 같은 형상인 것처럼 순회하고 싶을 때 np.broadcast_arrays가 편리합니다.

numpy
import numpy as np

# np.broadcast_to: explicit view of an array broadcast to a new shape
a = np.array([1, 2, 3])            # shape (3,)
b = np.broadcast_to(a, (4, 3))     # shape (4, 3) - VIEW, no copy
# [[1 2 3]
#  [1 2 3]
#  [1 2 3]
#  [1 2 3]]
b[0, 0] = 99   # ERROR: broadcast_to returns read-only view

# np.broadcast_arrays: broadcast several arrays together (as views)
x = np.array([1, 2, 3])           # (3,)
y = np.array([[10], [20]])        # (2, 1)
bx, by = np.broadcast_arrays(x, y)
bx.shape   # (2, 3)
by.shape   # (2, 3)

# np.broadcast: low-level iterator object
b = np.broadcast(x, y)
b.shape    # (2, 3)
b.index    # current position in the iteration
b.iters    # list of iterators over each input
06

수학 연산

요소별 산술

NumPy 연산자(+, *, **)는 ufunc(np.add, np.multiply, np.power)으로 매핑되며 요소별로 동작합니다. * 연산자는 요소별이며 '행렬 곱이 아닙니다'. 행렬 곱은 @ 또는 np.dot을 쓰세요. 제자리 연산자(+=, *=)는 배열 버퍼를 재사용해 메모리를 아낍니다. (broadcasting 후) dtype과 형상이 일치해야 합니다.

numpy
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])

a + b       # [11 22 33 44]
a - b       # [-9 -18 -27 -36]
a * b       # [10 40 90 160]   element-wise (NOT matrix product)
a / b       # [0.1 0.1 0.1 0.1]  always float
a // b      # [0 0 0 0]        floor division
a ** 2      # [1 4 9 16]       power
a % 2       # [1 0 1 0]        modulo
-a          # [-1 -2 -3 -4]    negation

# In-place ops (modify a, save memory)
a += 10
a *= 2

# Scalar ops broadcast
a + 100     # [102 104 106 108]

# Universal functions (ufuncs) - same operations as function form
np.add(a, b)
np.multiply(a, b)
np.power(a, 2)

범용 함수 (ufuncs)

ufunc는 요소별로 동작하는 벡터화 함수이며 컴파일된 C에서 실행됩니다. 루프에서 Python의 math 모듈을 적용하는 것보다 훨씬 빠릅니다. np.maximum(두 배열의 요소별 최대)은 np.max(한 배열의 최대)와 다릅니다. 비교에서 NaN을 무시하려 np.fmax를 쓰세요. 모든 ufunc는 out=을 지원해 미리 할당된 버퍼에 쓰므로 핫 루프에서 할당이 0이 됩니다.

numpy
import numpy as np
a = np.array([-1.5, 0.0, 1.5, 2.5])

# Math ufuncs
np.abs(a)         # [1.5 0.  1.5 2.5]
np.sqrt(np.abs(a))
np.exp(a)         # e^a
np.log(np.abs(a) + 1)
np.log2(a + 5)
np.log10(a + 5)

# Rounding
np.round(a)       # [-2.  0.  2.  2.]
np.floor(a)       # [-2.  0.  1.  2.]
np.ceil(a)        # [-1.  0.  2.  3.]
np.trunc(a)       # [-1.  0.  1.  2.]  truncate toward zero

# Trigonometry (radians)
np.sin(np.pi/2)   # 1.0
np.cos(0)         # 1.0
np.degrees(np.pi) # 180.0
np.radians(180)   # 3.14159...

# Comparison ufuncs
np.greater(a, 0)  # [False False True True]
np.maximum(a, 0)  # clip negatives to 0  (element-wise max)
np.minimum(a, 0)

축소(Reduction) 연산

축소(sum, mean, max, min, std)는 기본적으로 배열 전체 또는 axis=으로 한 축을 따라 동작합니다. axis=0은 행을 줄이고(아래로 접음) axis=1은 열을 줄입니다(가로로 접음). keepdims=True는 축소된 축을 크기 1로 유지하며 결과를 다시 broadcasting하는 데 필수입니다. 오버플로할 수 있는 정수 합산에는 항상 dtype=np.float64를 전달하세요.

numpy
import numpy as np
a = np.array([[1, 2, 3],
              [4, 5, 6]])

# Global reductions
a.sum()         # 21
a.prod()        # 720
a.min(), a.max()
a.mean()        # 3.5
a.std(), a.var()
a.argmin(), a.argmax()   # indices of min/max (flattened)

# Axis-wise reductions
a.sum(axis=0)   # [5 7 9]   sum down each column
a.sum(axis=1)   # [6 15]    sum across each row
a.min(axis=1)   # [1 4]     min of each row
a.cumsum(axis=0)   # cumulative sum down columns
a.cumprod(axis=1)  # cumulative product across rows

# Keep dimensions
a.sum(axis=0, keepdims=True)   # shape (1, 3) - keeps the axis

# Specify dtype for accumulation (avoid overflow!)
a.sum(dtype=np.float64)

# NaN-aware versions
b = np.array([1.0, np.nan, 3.0])
np.nansum(b)    # 4.0   treats NaN as 0

누적과 스캔 연산

cumsum / cumprod는 입력과 같은 형상을 유지하며 누계를 반환합니다. diff는 이산 도함수이며 cumsum의 역입니다. cumsum의 정수 오버플로에 주의하세요. int32 값의 누적은 조용히 wrap할 수 있으니 안전을 위해 int64나 float로 승격하세요. 임의 ufunc의 .accumulate 메서드(np.maximum.accumulate)가 누적 축소를 줍니다.

numpy
import numpy as np
a = np.array([1, 2, 3, 4, 5])

# Cumulative sum and product
np.cumsum(a)         # [ 1  3  6 10 15]
np.cumprod(a)        # [  1   2   6  24 120]

# 2-D: specify axis
b = np.array([[1, 2], [3, 4]])
np.cumsum(b, axis=0)   # [[1 2]
                       #  [4 6]]
np.cumsum(b, axis=1)   # [[1 3]
                       #  [3 7]]

# Differences (inverse of cumulative sum)
np.diff(a)            # [1 1 1 1]   a[i+1] - a[i]
np.diff(a, n=2)       # second-order diff [0 0 0]

# Edge: cumsum on integers can overflow silently
big = np.array([2**30, 2**30, 2**30], dtype=np.int32)
np.cumsum(big)        # wraps around - use int64 or float!

# Cumulative max / min
np.maximum.accumulate(a)   # [1 2 3 4 5]
np.minimum.accumulate(a)   # [1 1 1 1 1]

비교와 논리 연산

불리언 배열에는 & | ~를 쓰세요(and/or 아님. 이들은 단일 진리값이 필요). np.any / np.all은 불리언 배열을 단일 True/False로 축소하며 단언과 조건문에 유용합니다. 실수에 ==를 절대 쓰지 마세요. 적절한 허용 오차(atol/rtol)의 np.isclose나 np.allclose가 부동소수점 반올림을 처리합니다. allclose가 실수 배열 비교의 표준입니다.

numpy
import numpy as np
a = np.array([1, 2, 3, 4, 5])

# Element-wise comparisons return boolean arrays
a > 3            # [False False False  True  True]
a == 3           # [False False  True False False]
a != 3
np.greater(a, 3)

# Logical ops on boolean arrays
b = (a > 2)
c = (a < 5)
np.logical_and(b, c)   # [False False  True  True False]
np.logical_or(b, c)
np.logical_not(b)
np.logical_xor(b, c)

# Array-level truth testing
np.any(a > 4)    # True
np.all(a > 0)    # True
np.all(a > 0, axis=0)  # per-axis
(a == 3).any()   # True

# np.isclose for float comparisons
np.isclose(0.1 + 0.2, 0.3)        # True  (handles float error)
np.allclose([0.1, 0.2], [0.1, 0.2 + 1e-9], atol=1e-8)  # True
07

통계 연산

기본 통계

var/std는 기본 ddof=0(모집단)이지만 pandas는 기본 ddof=1(표본)이라 불일치가 자주 생깁니다. 표본 통계에는 ddof=1을 쓰세요. np.percentile은 0~100을, np.quantile은 0.0~1.0을 받습니다. np.corrcoef는 전체 상관 행렬을 반환하며 두 배열 간 스칼라 계수는 [0, 1] 인덱스입니다.

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

a.mean()          # 5.5    arithmetic mean
a.median() if hasattr(a, 'median') else np.median(a)  # 5.5
a.var()           # 8.25   variance (population, ddof=0)
a.std()           # 2.87   standard deviation
a.min(), a.max()  # 1, 10
a.ptp()           # 9      peak-to-peak = max - min

# Sample vs population variance
a.var(ddof=1)     # sample variance (divide by N-1, like pandas default)

# Percentiles & quantiles
np.percentile(a, 50)    # 5.5   median
np.percentile(a, [25, 50, 75])  # [3.25 5.5  7.75]  quartiles
np.quantile(a, 0.5)     # 5.5   same as percentile / 100

# Correlation
x = np.array([1, 2, 3, 4])
y = np.array([2, 4, 5, 4])
np.corrcoef(x, y)       # 2x2 correlation matrix

히스토그램과 binning

np.histogram은 개수와 경계를 반환합니다(edges가 bins보다 요소 하나 더 많음). 원시 개수 대신 확률 밀도(면적 = 1)를 얻으려 density=True를 쓰세요. np.histogram2d는 히트맵과 결합 분포에 유용한 2차원 히스토그램을 만듭니다. np.digitize는 값을 bin 인덱스로 매핑하고, np.bincount는 정수 발생 횟수 세기의 빠른 방법입니다.

numpy
import numpy as np
data = np.random.default_rng(42).standard_normal(1000)

# 1-D histogram
counts, edges = np.histogram(data, bins=10)
# counts: array of element counts per bin
# edges: array of bin edge positions (length = bins + 1)

# Custom bin edges
np.histogram(data, bins=[-3, -1, 0, 1, 3])

# Density (integrates to 1) vs counts
np.histogram(data, bins=20, density=True)

# 2-D histogram (for heatmaps)
x = np.random.default_rng(1).standard_normal(1000)
y = np.random.default_rng(2).standard_normal(1000)
H, xedges, yedges = np.histogram2d(x, y, bins=20)

# Digitize: which bin does each value fall into?
bins = [-2, -1, 0, 1, 2]
indices = np.digitize(data, bins)   # array of bin indices (1-based)

# Bincount: count occurrences of each non-negative int
np.bincount(np.array([0, 1, 1, 3, 3, 3]))   # [1 2 0 3]

정렬과 순서 통계

argsort가 순위 매기기의 열쇠입니다. 배열을 정렬할 인덱스를 반환해 다른 배열을 같은 방식으로 재정렬할 수 있게 합니다. 상위 k개만 필요할 때 np.partition은 전체 정렬보다 훨씬 빠릅니다(O(n) vs O(n log n)). np.unique는 정렬된 고유 값을 반환하며 return_counts=True를 주면 히스토그램 같은 요약이 됩니다.

numpy
import numpy as np
a = np.array([3, 1, 4, 1, 5, 9, 2, 6])

# Sorting
np.sort(a)             # [1 1 2 3 4 5 6 9]   returns a copy
a.sort()               # in-place sort (modifies a)
np.sort(a)[::-1]       # descending
np.argsort(a)          # indices that would sort a (no copy)

# 2-D sorting along axis
b = np.array([[3, 1, 2], [6, 5, 4]])
np.sort(b, axis=0)     # sort down each column
np.sort(b, axis=1)     # sort across each row (default)

# Partial sorting: top-k smallest (no full sort)
np.partition(a, 3)     # 3 smallest first (unordered), rest after
np.argpartition(a, 3)  # indices of partition

# k-th smallest element (selection algorithm)
np.partition(a, 2)[2]  # 3rd smallest (index 2)

# unique values (sorted)
np.unique([1, 2, 1, 3, 2])   # [1 2 3]
np.unique(a, return_counts=True)  # values and counts

공분산과 상관

np.cov는 기본적으로 각 '행'을 변수로 취급합니다(rowvar=True). 컬럼을 쓰는 pandas와 반대입니다. pandas 동작에 맞추려 rowvar=False를 전달하거나 데이터를 전치하세요. np.corrcoef는 전체 행렬을 반환하며 두 변수 간 스칼라 계수는 [0, 1] 인덱스입니다. 공분산 행렬의 대각선은 각 변수의 분산입니다.

numpy
import numpy as np
# Sample data: 3 variables, 5 observations
data = np.array([[1, 2, 3, 4, 5],
                 [2, 4, 1, 3, 5],
                 [5, 4, 3, 2, 1]], dtype=float)

# Covariance matrix (3x3)
# Each ROW is a variable, so set rowvar=False to treat COLUMNS as variables
cov = np.cov(data, rowvar=True)   # 3x3 covariance between rows
# Diagonal = variance of each variable
# Off-diagonal = covariance between pairs

# Correlation matrix
corr = np.corrcoef(data)   # 3x3, values in [-1, 1]

# Correlation between two specific variables
np.corrcoef(data[0], data[1])[0, 1]   # scalar

# Weighted covariance: compute manually
weights = np.array([1, 1, 1, 2, 2])
mean = np.average(data, axis=1, weights=weights, keepdims=True)
centered = data - mean
weighted_cov = (centered * weights) @ centered.T / weights.sum()

# Pearson correlation coefficient (manual)
def pearson(x, y):
    xm, ym = x - x.mean(), y - y.mean()
    return np.dot(xm, ym) / (np.sqrt((xm**2).sum()) * np.sqrt((ym**2).sum()))

NaN 인식 통계

표준 축소는 NaN을 전파합니다(하나의 NaN이 결과를 오염). 원하는 것은 거의 아닙니다. NaN을 무시하려 nan* 변형(nanmean, nansum, nanstd)을 쓰세요. nan_to_num은 NaN과 무한대를 유한 값으로 교체하며 계산 전 데이터 정제에 완벽합니다. NaN 처리가 많으면 원시 NumPy보다 pandas가 더 인체공학적입니다.

numpy
import numpy as np
a = np.array([1.0, 2.0, np.nan, 4.0, 5.0])

# Standard functions propagate NaN
a.mean()      # nan
a.sum()       # nan

# NaN-aware equivalents
np.nanmean(a)     # 3.0   ignores NaN
np.nansum(a)      # 12.0
np.nanstd(a)
np.nanmedian(a)
np.nanvar(a)
np.nanmin(a), np.nanmax(a)
np.nanpercentile(a, 50)

# Count non-NaN elements
np.count_nonzero(~np.isnan(a))   # 4

# Find NaN positions
np.isnan(a)            # [False False  True False False]
np.where(np.isnan(a))  # (array([2]),)

# Replace NaN with a value (imputation)
np.nan_to_num(a, nan=0.0)              # replace NaN with 0
np.where(np.isnan(a), 0, a)            # same, more explicit
a_filled = np.copy(a)
a_filled[np.isnan(a)] = np.nanmean(a)  # fill with mean

# Check if any NaN
np.isnan(a).any()      # True
08

선형 대수 (numpy.linalg)

행렬 곱

행렬 곱에는 @를 쓰세요. 현대 연산자(Python 3.5+)이며 .dot()보다 명확하고 배칭(N차원) 연산에도 동작합니다. * 연산자는 요소별(Hadamard)이며 MATLAB 출신에게 흔한 혼란의 원천입니다. np.matmul(@)은 1차원 처리와 N차원 배열의 스태킹 동작에서 np.dot과 다릅니다.

numpy
import numpy as np

A = np.array([[1, 2],
              [3, 4]])
B = np.array([[5, 6],
              [7, 8]])

# Matrix product (2-D)
A @ B                  # [[19 22]
                       #  [43 50]]    preferred operator (Py 3.5+)
A.dot(B)               # same, older method
np.dot(A, B)           # same for 2-D

# 1-D: dot is inner product
v = np.array([1, 2, 3])
w = np.array([4, 5, 6])
v @ w                  # 32   (1*4 + 2*5 + 3*6)
np.dot(v, w)           # 32

# Mixed 1-D and 2-D
v = np.array([1, 2])
A @ v                  # [5 11]   matrix-vector product

# Batched matmul (3-D)
X = np.random.rand(10, 3, 4)   # 10 matrices of shape (3, 4)
Y = np.random.rand(10, 4, 2)
(X @ Y).shape          # (10, 3, 2)

# Element-wise product (Hadamard) - NOT matrix product
A * B                  # [[5 12]
                       #  [21 32]]

분해 (LU, QR, SVD)

SVD가 가장 안정적인 분해이며 어떤 행렬에도 동작하니 확신이 없을 때 쓰세요. 고유 분해는 정사각 행렬에만 동작하고 결함 행렬에서 수치적으로 불안정할 수 있습니다. Cholesky는 대칭 양정치 행렬(공분산과 최적화에서 흔함)에 가장 빠릅니다. QR은 최소제곱과 직교화에 유용합니다.

numpy
import numpy as np
A = np.array([[4, 3],
              [6, 3]])

# SVD: A = U @ diag(s) @ Vt
U, s, Vt = np.linalg.svd(A)
# U: (2,2) left singular vectors
# s: (2,) singular values (sorted descending)
# Vt: (2,2) right singular vectors (already transposed)

# Reconstruct A from SVD
A_reconstructed = U @ np.diag(s) @ Vt
np.allclose(A, A_reconstructed)   # True

# QR decomposition: A = Q @ R
Q, R = np.linalg.qr(A)
# Q: orthonormal columns
# R: upper triangular

# Cholesky (for symmetric positive-definite matrices)
S = A @ A.T   # symmetric positive-definite
L = np.linalg.cholesky(S)
np.allclose(S, L @ L.T)   # True

# Eigen-decomposition (square matrices)
w, V = np.linalg.eig(A)
# w: eigenvalues
# V: eigenvectors as columns

# Eigenvalues only (faster)
np.linalg.eigvals(A)

선형 시스템 해와 역행렬

역행렬 계산보다 np.linalg.solve을 항상 선호하세요. 더 빠르고 수치적으로 더 안정하며 거특이 행렬의 함정을 피합니다. 실무에서 역행렬은 거의 필요 없습니다. inv(A) @ b를 쓰고 있다면 solve(A, b)로 바꾸세요. pinv는 SVD로 직사각 및 특이 행렬을 처리합니다. cond(A)를 확인하세요. 큰 조건수(>1e10)는 시스템이 수치적으로 나쁘다는 뜻입니다.

numpy
import numpy as np

A = np.array([[3, 2],
              [1, 4]])
b = np.array([7, 6])

# Solve Ax = b (preferred - no explicit inverse)
x = np.linalg.solve(A, b)        # [1.6 1.1]
np.allclose(A @ x, b)            # True

# Multiple right-hand sides
B = np.array([[7, 1], [6, 2]])   # 2x2
X = np.linalg.solve(A, B)        # 2x2 solution matrix

# Inverse (avoid if you only need to solve Ax=b)
A_inv = np.linalg.inv(A)
A_inv @ b    # same result as solve, but slower & less stable

# Pseudo-inverse (works for non-square / singular matrices)
A_pinv = np.linalg.pinv(A)       # Moore-Penrose pseudo-inverse

# Determinant
np.linalg.det(A)    # 10.0

# Matrix rank
np.linalg.matrix_rank(A)   # 2

# Condition number (large = ill-conditioned)
np.linalg.cond(A)   # ~1.9

노름과 벡터 연산

norm은 벡터에는 L2, 행렬에는 Frobenius가 기본이며 프로덕션 코드에서는 명확히 ord를 지정하세요. 맨해튼(택시) 거리는 ord=1, 체비셰프(최대절대값) 거리는 ord=np.inf입니다. 외적은 3차원 벡터에서만 동작합니다. 많은 점 간 쌍별 거리에는 norm을 루프로 도는 것보다 scipy.spatial.distance.cdist가 빠릅니다.

numpy
import numpy as np
v = np.array([3, 4])

# Vector norms
np.linalg.norm(v)         # 5.0    L2 (Euclidean) - default
np.linalg.norm(v, ord=1)  # 7.0    L1 (sum of |x|)
np.linalg.norm(v, ord=np.inf)  # 4.0  L-infinity (max |x|)

# Matrix norms
A = np.array([[1, 2], [3, 4]])
np.linalg.norm(A)         # Frobenius norm (default for matrices)
np.linalg.norm(A, ord='fro')
np.linalg.norm(A, ord=2)  # spectral norm (largest singular value)
np.linalg.norm(A, ord=np.inf)  # max row sum

# Normalizing a vector (unit vector)
v / np.linalg.norm(v)

# Distance between two vectors
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
np.linalg.norm(a - b)         # Euclidean distance
np.linalg.norm(a - b, ord=1)  # Manhattan distance

# Outer product, cross product
np.cross([1, 0, 0], [0, 1, 0])   # [0 0 1]   (3-D only)
np.outer([1, 2], [10, 20, 30])   # (2, 3)

최소제곱과 회귀

np.linalg.lstsq는 정규 방정식을 만들지 않고 최소제곱 문제를 풉니다(더 안정). 해, 잔차, 랭크, 특잇값을 반환하므로 랭크 부족 문제 진단에 유용합니다. 다항식 피팅에는 polyfit + poly1d가 편리한 API이지만 고차 다항식의 수치 불안정에 주의하세요. 진지한 작업에는 수치 조건이 더 좋은 numpy.polynomial.Polynomial을 쓰세요.

numpy
import numpy as np

# Linear least squares: solve Ax = b for over-determined A (more rows than cols)
# Minimizes ||Ax - b||^2
A = np.array([[1, 1],
              [1, 2],
              [1, 3],
              [1, 4]])         # design matrix (4x2)
b = np.array([6, 5, 7, 10])    # observations

x, residuals, rank, sv = np.linalg.lstsq(A, b, rcond=None)
# x: best-fit parameters [intercept, slope] = [3.5, 1.4]
# residuals: sum of squared errors
# rank: effective rank of A
# sv: singular values of A

# Polynomial fitting (least squares under the hood)
x_data = np.array([0, 1, 2, 3, 4])
y_data = np.array([1, 3, 7, 13, 21])
coeffs = np.polyfit(x_data, y_data, deg=2)   # quadratic fit
# coeffs[0]*x^2 + coeffs[1]*x + coeffs[2]

# Evaluate polynomial
poly = np.poly1d(coeffs)
poly(2.5)   # predict y at x=2.5

# Polynomial roots (zeros)
np.roots([1, -3, 2])   # roots of x^2 - 3x + 2 = 0 -> [2, 1]
09

랜덤 수

현대 Generator (default_rng)

np.random.default_rng가 현대적 권장 API입니다. 레거시 np.random.* 함수보다 빠르고 통계적 특성이 더 좋으며 명시적 Generator 객체를 써서(숨은 전역 상태 없음) 재현성과 병렬화가 훨씬 쉽습니다. 재현 가능한 연구와 테스트를 위해 항상 명시적 seed를 전달하세요.

numpy
import numpy as np

# Create a Generator with a seed (modern API, NumPy >= 1.17)
rng = np.random.default_rng(seed=42)

# Uniform [0, 1) floats
rng.random()              # scalar
rng.random(size=5)        # 1-D array of 5
rng.random((3, 4))        # 3x4 array

# Standard normal (mean 0, std 1)
rng.standard_normal(5)
rng.standard_normal((2, 3))

# Integers in [low, high)
rng.integers(0, 10, size=5)       # 5 random ints in [0, 10)
rng.integers(1, 7, size=(2, 3), endpoint=True)  # include 7

# Choice: sample from an array
rng.choice([10, 20, 30, 40], size=5)
rng.choice([10, 20, 30, 40], size=5, replace=True)   # default
rng.choice(range(100), size=10, replace=False)        # without replacement

# Why default_rng? Faster, better statistical properties, no global state.
# Legacy np.random.rand/randn/seed still works but is discouraged.

흔한 분포

NumPy는 Generator API로 수십 개 분포를 제공합니다. 파라미터는 통계 관례를 따릅니다(정규는 loc=평균, scale=표준편차, 포아송은 lam=lambda). multivariate_normal은 공분산 행렬이 필요하며 지정된 상관 구조를 가진 샘플을 반환합니다. shuffle은 제자리 수정이고 permutation은 새 배열을 반환합니다.

numpy
import numpy as np
rng = np.random.default_rng(42)

# Continuous distributions
rng.uniform(0, 10, size=5)        # uniform in [low, high)
rng.normal(loc=100, scale=15, size=5)   # normal(mu, sigma)
rng.standard_normal(size=5)       # standard normal
rng.exponential(scale=2.0, size=5)   # exponential
rng.gamma(shape=2.0, scale=1.5, size=5)
rng.beta(a=2, b=5, size=5)
rng.lognormal(mean=0.0, sigma=1.0, size=5)
rng.chisquare(df=3, size=5)
rng.standard_t(df=10, size=5)

# Discrete distributions
rng.binomial(n=10, p=0.5, size=5)
rng.poisson(lam=3.0, size=5)
rng.geometric(p=0.1, size=5)
rng.negative_binomial(n=5, p=0.5, size=5)

# Multi-variate normal
mean = [0, 0]
cov = [[1, 0.5], [0.5, 1]]
rng.multivariate_normal(mean, cov, size=1000)   # shape (1000, 2)

# Shuffle & permutation (in-place / copy)
arr = np.arange(10)
rng.shuffle(arr)        # in-place shuffle
perm = rng.permutation(10)   # returns a new array

재현성과 seed

재현 가능한 실험을 위해 seed와 NumPy 버전을 모두 고정하세요. 랜덤 수 스트림은 NumPy 릴리스 간 바뀔 수 있습니다. 병렬 컴퓨팅에서는 spawn()으로 독립 자식 스트림을 만드세요. 워커 인덱스를 seed에 단순히 더하는 것은 금물입니다(충돌이 생각보다 흔함). SeedSequence가 엔트로피 분할을 올바르게 처리합니다.

numpy
import numpy as np

# Same seed -> same sequence of random numbers
r1 = np.random.default_rng(42)
r2 = np.random.default_rng(42)
print(r1.random(3))    # [0.7739 0.4389 0.8586]
print(r2.random(3))    # same exact values

# Different seeds -> independent sequences
r3 = np.random.default_rng(123)
print(r3.random(3))    # different values

# Seed from entropy (non-reproducible) - default if seed omitted
r4 = np.random.default_rng()    # seeded from OS entropy

# Spawn independent child generators (for parallelism)
parent = np.default_rng(42)
children = parent.spawn(4)   # 4 independent Generators
# Each child produces an independent, reproducible stream

# SeedSequence for advanced control
ss = np.random.SeedSequence(42)
child_seeds = ss.spawn(4)
streams = [np.random.default_rng(s) for s in child_seeds]

# Reproducibility across versions: pin numpy version too!

셔플, 치환, 샘플링

rng.permutation(indices)을 쓰고 데이터를 fancy-index하세요. 학습 전 데이터셋을 셔플하는 정석 패턴입니다. replace=False를 준 choice가 비복원 추출이며, p=으로 커스텀 확률로 추출할 수 있습니다. 부트스트랩에는 복원 추출을 위한 rng.integers를 쓰세요(한 값이 여러 번 나올 수 있음).

numpy
import numpy as np
rng = np.random.default_rng(42)

# Shuffle (in-place)
a = np.arange(10)
rng.shuffle(a)         # a is now shuffled

# Permutation (returns a new array, original untouched)
b = np.arange(10)
perm = rng.permutation(b)
# b is unchanged, perm is the shuffled version

# Permutation of indices (common pattern for shuffling a dataset)
idx = rng.permutation(100)
X_shuffled = X[idx]
y_shuffled = y[idx]

# Random choice
rng.choice(100, size=10, replace=False)   # 10 unique indices
rng.choice([1, 2, 3], size=10, p=[0.1, 0.3, 0.6])  # weighted

# Sample rows of a 2-D array
data = np.arange(20).reshape(10, 2)
row_idx = rng.choice(10, size=3, replace=False)
sample = data[row_idx]    # 3 random rows

# Bootstrap sampling (with replacement)
boot_idx = rng.integers(0, len(data), size=len(data))
boot_sample = data[boot_idx]

랜덤 상태 설정 (레거시 API)

레거시 np.random.seed/rand/randn API는 전역 가변 상태를 씁니다. REPL에서는 편리하지만 라이브러리와 병렬 코드에서는 취약합니다. 레거시 API를 꼭 써야 한다면 전역 상태를 수정하지 말고 명시적 RandomState 객체를 만드세요. 새 코드에는 항상 default_rng를 쓰세요. 인자 관례가 조금 다릅니다(randint는 기본 상한 제외, integers는 endpoint=True일 때만 상한 포함).

numpy
import numpy as np

# Legacy global-state API (still common in old code)
np.random.seed(42)
a = np.random.rand(3)      # [0.3745 0.9507 0.7320]

np.random.seed(42)
b = np.random.rand(3)      # same as a - global state was reset

# Functions operate on the global RandomState
np.random.rand(2, 3)       # uniform [0, 1)
np.random.randn(2, 3)      # standard normal
np.random.randint(0, 10, 5)
np.random.choice([1, 2, 3], 2)
np.random.shuffle(arr)

# Create an independent RandomState (better than global)
rs = np.random.RandomState(42)
rs.rand(3)                 # independent of np.random's global state

# Migration: replace np.random.X(args) with rng.X(args)
# rng = np.random.default_rng(seed)
# rand()       -> random()
# randn()      -> standard_normal()
# randint(a,b) -> integers(a, b)   # note: endpoint differs
# seed(s)      -> default_rng(s)   # explicit Generator
10

고급 인덱싱

Fancy 인덱싱 상세

정수 배열의 fancy 인덱싱은 주어진 위치의 요소를 선택하며 항상 복사본을 반환합니다. 두 인덱스 배열로 2차원 배열을 인덱싱하면 배열이 요소별로 짝지어집니다(점). 곱집합이 아닙니다. 행 × 열의 직사각형은 np.ix_를 쓰세요. fancy 인덱싱이 비연속 또는 반복 요소를 선택하는 유일한 방법입니다.

numpy
import numpy as np
a = np.arange(10, 20)   # [10 11 12 13 14 15 16 17 18 19]

# Index with integer arrays
indices = np.array([0, 3, 5, 8])
a[indices]              # [10 13 15 18]

# Negative indices
a[[-1, -2, -3]]         # [19 18 17]

# Index arrays can repeat (creates duplicates)
a[[0, 0, 1, 1]]         # [10 10 11 11]

# Assign through fancy indexing
a[[0, 3, 5]] = -1       # set those positions to -1
a[[1, 2]] = [100, 200]  # different value per position

# 2-D: pair (row, col) indices element-wise
b = np.arange(12).reshape(3, 4)
rows = np.array([0, 1, 2])
cols = np.array([1, 2, 3])
b[rows, cols]           # [1 6 11]  points (0,1), (1,2), (2,3)

# For a cross-product (rectangle) use np.ix_
b[np.ix_([0, 2], [1, 3])]
# [[ 1  3]
#  [ 9 11]]

불리언 배열 심화

불리언 인덱싱은 입력 차원과 무관하게 매칭 요소의 1차원 배열을 항상 복사본으로 반환합니다. 조건 결합에는 & | ~(비트 연산자)을 쓰고 단일 불리언 값이 필요한 and/or가 아닙니다. 2차원 배열의 1차원 불리언 마스크는 행 전체를 선택합니다. True == 1이므로 True 개수는 .sum()으로 셉니다.

numpy
import numpy as np
a = np.array([5, 10, 15, 20, 25, 30])

# Boolean mask
mask = a > 15
a[mask]                  # [20 25 30]
a[a > 15]                # equivalent

# Multiple conditions: use & | ~ (NOT and/or)
a[(a > 10) & (a < 30)]   # [15 20 25]
a[(a < 10) | (a > 25)]   # [5 30]
a[~(a > 15)]             # [5 10 15]  negation

# Count True
mask.sum()               # 3   (True == 1)

# Boolean indexing returns a COPY (not a view)
b = a[a > 15]
b[0] = 999
print(a[3])              # 20  - a unchanged

# 2-D boolean mask (must match array shape)
M = np.arange(12).reshape(3, 4)
mask2d = M > 5
M[mask2d]                # 1-D array of matching values (flattened)

# Row selection with a 1-D boolean mask
row_mask = np.array([True, False, True])
M[row_mask]              # rows 0 and 2

np.where과 np.choose

np.where가 가장 흔한 조건문입니다. 인자 셋이면 벡터화된 if-else이고, 인자 하나면 True 값의 인덱스를 반환합니다. 여러 상호배타적 조건에는 중첩 np.where 호출보다 np.select가 깔끔합니다. np.choose는 덜 흔하지만 정수 인덱스로 두 개 이상의 배열에서 선택할 때 유용합니다.

numpy
import numpy as np
a = np.array([1, 2, 3, 4, 5])

# np.where(cond) -> indices where cond is True
np.where(a > 3)             # (array([3, 4]),)   tuple of index arrays

# np.where(cond, x, y) -> vectorized ternary
np.where(a > 3, "big", "small")
# ['small' 'small' 'small' 'big' 'big']

# np.where with arrays for x and y
np.where(a % 2 == 0, a * 10, a)   # double the evens, keep odds

# Multi-dim where
M = np.array([[1, 2], [3, 4]])
np.where(M > 2)             # (array([1, 1]), array([0, 1]))  (row, col) pairs

# np.choose: pick from multiple arrays based on integer index
choices = [[10, 20, 30], [100, 200, 300], [1000, 2000, 3000]]
np.choose([0, 2, 1], choices)   # [10 2000 300]

# np.select: multiple conditions
conds = [a < 3, a > 4, (a >= 3) & (a <= 4)]
choices = ["low", "high", "mid"]
np.select(conds, choices)   # ['low' 'mid' 'mid' 'mid' 'high']

np.ix_ 인덱싱

행과 열 인덱스 목록으로 직사각형 서브 블록을 선택할 때 np.ix_가 필수입니다. 없으면 두 인덱스 배열이 요소별로 짝지어져 격자가 아니라 점이 됩니다. 가장 흔한 NumPy 함정 중 하나입니다. 같은 트릭이 불리언 마스크로 행과 열을 동시에 선택할 때도 동작합니다.

numpy
import numpy as np
a = np.arange(20).reshape(4, 5)

# Select rows 0 and 2, columns 1 and 3 (cross product)
rows = [0, 2]
cols = [1, 3]
a[np.ix_(rows, cols)]
# [[ 1  3]
#  [11 13]]

# Without np.ix_, fancy indexing pairs the arrays element-wise:
a[np.array(rows), np.array(cols)]
# ERROR (or wrong result): pairs (0,1) and (2,3) - points, not rectangle

# Boolean masks also work with np.ix_
row_mask = np.array([True, False, True, False])
col_mask = np.array([False, True, False, True, False])
a[np.ix_(row_mask, col_mask)]   # rows where True, cols where True

# 3-D indexing with ix_
b = np.arange(24).reshape(2, 3, 4)
b[np.ix_([0], [0, 2], [1, 3])].shape   # (1, 2, 2)

# np.ix_ converts 1-D index arrays into broadcastable open grids
# so the result is a (Cartesian) rectangle, not points

메모리 배치와 뷰

기본 슬라이싱은 뷰(메모리 공유)를 반환하고 fancy/불리언 인덱싱은 복사본을 반환합니다. 두 배열이 겹치는지 확인하려 np.shares_memory를 쓰세요. 제자리 연산과 수정이 전파될지 이해하는 데 중요합니다. 핫 루프에서 최상위 성능이 필요하면 np.ascontiguousarray가 메모리를 연속으로 만들어 C 수준 루프가 간접 참조 없이 실행하게 합니다.

numpy
import numpy as np
a = np.arange(12).reshape(3, 4)

# Most slicing returns VIEWS (no data copy)
v = a[1:, 1:]   # view
v[0, 0] = 99
print(a[1, 1])  # 99   - a was modified

# Fancy and boolean indexing always return COPIES
b = a[[0, 1, 2]]
b[0] = -1
print(a[0, 0])  # 0   - a unchanged

# Check if two arrays share memory
np.shares_memory(a, v)   # True
np.shares_memory(a, b)   # False

# Force a copy with .copy()
independent = a[1:, 1:].copy()

# Memory layout flags
a.flags['C_CONTIGUOUS']    # True  - row-major (C order)
a.flags['F_CONTIGUOUS']    # False - column-major (Fortran)

# Convert to a guaranteed-contiguous array (sometimes speeds up ops)
a_contig = np.ascontiguousarray(a)
a_fortran = np.asfortranarray(a)

# may_share_memory: weaker, faster check
np.may_share_memory(a, v)  # True
11

배열 I/O

.npy / .npz 저장과 로드

.npy는 단일 배열을, .npz는 여러 이름 붙은 배열을 zip 컨테이너에 저장합니다. savez_compressed는 CPU 시간을 대가로 더 작은 파일을 만듭니다. np.load가 돌려준 NpzFile은 지연이며 배열은 처음 접근할 때 로드되므로 파일 핸들이 닫히도록 with 블록을 쓰세요. 이 바이너리 형식은 CSV/텍스트와 달리 dtype과 shape을 정확히 보존합니다.

numpy
import numpy as np
a = np.arange(12).reshape(3, 4)
b = np.array([1, 2, 3])

# Save a single array (binary .npy format)
np.save("a.npy", a)
loaded = np.load("a.npy")
np.array_equal(a, loaded)   # True

# Save multiple arrays (zipped .npz)
np.savez("data.npz", a=a, b=b, c=np.zeros(3))
data = np.load("data.npz")
print(data["a"])   # the saved array a
print(data["b"])   # array b
print(list(data.keys()))   # ['a', 'b', 'c']

# Compressed savez
np.savez_compressed("data.npz", a=a, b=b)   # smaller file, slower

# Loading returns a lazy NpzFile - arrays load on access
# Close it explicitly if you have many files open
with np.load("data.npz") as data:
    a = data["a"]
    b = data["b"]
# file handle auto-closed after the with block

텍스트 파일 (CSV, TSV)

np.savetxt/loadtxt는 1차원과 2차원 배열만 다룹니다. 더 높은 차원은 .npy/.npz를 쓰세요. genfromtxt는 결측값과 이질적 타입에 더 관대하지만 큰 파일에서 느립니다. 실제 CSV 작업에는 pandas.read_csv가 훨씬 빠르고 기능이 풍부하며, 정제가 끝나면 .to_numpy()로 NumPy로 변환하세요.

numpy
import numpy as np

# Save as plain text (1-D or 2-D only)
a = np.arange(12).reshape(3, 4)
np.savetxt("a.csv", a, delimiter=",", fmt="%d",
           header="col1,col2,col3,col4", comments="")

# Load text
loaded = np.loadtxt("a.csv", delimiter=",", skiprows=1, dtype=int)

# genfromtxt: handles missing values and irregular data
data = np.genfromtxt("data.csv", delimiter=",",
                     names=True,          # first row = field names
                     dtype=None,          # infer types per column
                     missing_values="",
                     filling_values=0)
# data is a structured array; access columns by name
print(data["age"])

# More flexible: pandas.read_csv, then convert to NumPy
import pandas as pd
df = pd.read_csv("data.csv")
arr = df.to_numpy()      # 2-D ndarray
ages = df["age"].to_numpy()   # 1-D

메모리 매핑 파일

np.memmap은 디스크 파일을 메모리로 매핑해 RAM보다 큰 배열을 다루게 합니다. 접근된 페이지만 로드됩니다. 멀티GB 데이터셋에 필수입니다. 쓰기 후 flush()를 호출하고 파일 핸들을 해제하려 memmap을 del하거나 close하세요. 슬라이싱은 필요한 페이지만 읽지만 fancy 인덱싱은 전체 로드를 강제할 수 있습니다.

numpy
import numpy as np

# Create a large array on disk (without loading it all into RAM)
shape = (10000, 10000)
dtype = np.float64
mm = np.memmap("big.dat", dtype=dtype, mode="w+", shape=shape)

# Write to it as if it were a normal array
mm[:] = np.arange(shape[0])[:, None] + np.arange(shape[1])[None, :]
mm.flush()   # flush changes to disk

# Re-open for reading without loading the whole file
mm_read = np.memmap("big.dat", dtype=dtype, mode="r", shape=shape)
print(mm_read[0, 0])    # access a small slice -> only that page loads
print(mm_read[-1, -1])

# Mode: 'r' (read-only), 'r+' (read/write), 'w+' (create/overwrite)
# Slicing a memmap returns a normal ndarray (copy) or a memmap view
# depending on the operation.

# Useful for processing huge datasets that don't fit in RAM
# (e.g. iterating over chunks of a multi-GB array)

다른 라이브러리와의 상호운용

대부분의 ML 라이브러리는 NumPy와 (제로카피로) 메모리를 공유합니다. torch.from_numpy와 tf.constant가 같은 버퍼를 감싸 한쪽 수정이 다른 쪽에 영향을 줍니다. PyTorch GPU 텐서는 .numpy() 전에 CPU로 옮겨야 합니다. 원시 바이트(예: 소켓 전송)가 필요하면 직렬화에 tobytes / frombuffer를 쓰세요. 변환 후 항상 shape과 dtype을 검증하세요.

numpy
import numpy as np
import pandas as pd

# NumPy <-> pandas
df = pd.DataFrame({"a": [1, 2, 3], "b": [4.0, 5.0, 6.0]})
arr = df.to_numpy()      # 2-D float array
col = df["a"].to_numpy() # 1-D int array
df2 = pd.DataFrame(arr, columns=["x", "y"])

# NumPy <-> PyTorch
import torch
t = torch.from_numpy(arr)     # shares memory (no copy)
back = t.numpy()              # only works for CPU tensors

# NumPy <-> TensorFlow
import tensorflow as tf
tensor = tf.constant(arr)
back = tensor.numpy()

# NumPy <-> JAX
import jax.numpy as jnp
j_arr = jnp.asarray(arr)      # JAX array (immutable)

# NumPy <-> bytes (for serialization / network)
buf = arr.tobytes()
restored = np.frombuffer(buf, dtype=arr.dtype).reshape(arr.shape)

# Convert list of arrays to a single array (must be same shape)
list_of_arrays = [np.array([1, 2]), np.array([3, 4])]
np.array(list_of_arrays)   # shape (2, 2)

구조화 배열 I/O

구조화 배열은 이질적 레코드형 데이터를 NumPy에 저장하게 합니다. pandas가 과분하거나 사용 불가할 때 유용합니다. 바이너리 .npy 형식은 구조화 dtype을 정확히 보존합니다. 실제 테이블 작업에는 pandas가 거의 항상 더 낫습니다. 구조화 배열은 C/Fortran 코드와의 저수준 상호운용이나 메모리가 극도로 빠듯할 때 쓰세요.

numpy
import numpy as np

# Define a structured dtype
dt = np.dtype([("name", "U20"), ("age", "i4"), ("score", "f4")])
data = np.array([("Alice", 30, 9.5),
                 ("Bob", 25, 8.0),
                 ("Carol", 35, 9.8)], dtype=dt)

# Save / load (binary preserves structure)
np.save("people.npy", data)
loaded = np.load("people.npy")
print(loaded["name"])   # ['Alice' 'Bob' 'Carol']
print(loaded["age"].mean())   # 30.0

# CSV with mixed types: better to use pandas
import pandas as pd
df = pd.DataFrame(data)
df.to_csv("people.csv", index=False)

# Convert a structured array to a regular 2-D array
arr_2d = data.view([("age", "i4"), ("score", "f4")]).reshape(-1)  # view
# or just stack the numeric columns
numeric = np.column_stack([data["age"], data["score"]])

# Sort by a field
sorted_data = np.sort(data, order="score")   # ascending by score
sorted_data[-1]["name"]   # 'Carol'
12

Datetime 연산

Datetime 배열 생성

NumPy datetime64는 고정 폭(8바이트) datetime으로 Python datetime 객체보다 훨씬 효율적입니다. 단위 접미사로 정밀도를 지정하세요. [Y]년, [M]월, [D]일, [h]시, [m]분, [s]초, [ms]밀리초. np.arange는 datetime64와 함께 동작해 날짜 범위를 생성합니다.

numpy
import numpy as np

# From ISO strings
dates = np.array(["2024-01-15", "2024-02-20", "2024-03-25"],
                 dtype="datetime64[D]")
# dtype [D] = day precision

# Different precisions
np.datetime64("2024-01-15")              # day precision
np.datetime64("2024-01-15T10:30")        # minute precision
np.datetime64("2024-01-15T10:30:45.123") # ms precision

# Array of datetimes
np.array(["2024-01", "2024-02", "2024-03"], dtype="datetime64[M]")

# Arange with datetime
np.arange("2024-01", "2024-06", dtype="datetime64[M]")
# ['2024-01' '2024-02' '2024-03' '2024-04' '2024-05']

# Today (UTC)
np.datetime64("today", "D")
np.datetime64("now", "s")

Timedelta 산술

두 datetime64 배열의 차는 timedelta64 배열입니다. NumPy는 (월 길이가 다르므로) 월과 년 산술을 올바르게 처리합니다. np.busday_offset과 np.is_busday가 주말과 선택적 휴일을 건너뛰는 영업일 로직을 제공합니다. 더 정교한 영업 달력 지원은 pandas의 CustomBusinessDay를 쓰세요.

numpy
import numpy as np

start = np.datetime64("2024-01-01")
end = np.datetime64("2024-12-31")

# Difference is a timedelta64
diff = end - start
print(diff, diff.dtype)   # 365 days, timedelta64[D]

# Add / subtract timedeltas
start + np.timedelta64(7, "D")       # 2024-01-08
start + np.timedelta64(1, "M")       # 2024-02-01 (month added)
start + np.timedelta64(2, "h")       # 2024-01-01T02:00

# Business day arithmetic
np.busday_offset("2024-01-15", 1)     # next business day
np.is_busday("2024-01-15")            # Monday -> True
np.is_busday("2024-01-13")            # Saturday -> False

# Count business days in a range
np.busday_count("2024-01-01", "2024-02-01")   # 23

# Array of business days
np.arange("2024-01-01", "2024-01-10", dtype="datetime64[D]")
# [Mon Tue Wed Thu Fri Sat Sun Mon Tue]

날짜 범위와 리샘플링

NumPy의 datetime64는 범위 생성과 기본 산술을 지원하지만 리샘플링, 그룹핑, 시간대 처리는 pandas가 훨씬 강력합니다. 패턴: 무거운 날짜 조작은 pandas에서 하고, 원시 성능이 필요하면 .to_numpy()로 NumPy datetime64로 되돌립니다. NumPy datetime64는 항상 시간대 무지(tz-naive, UTC)입니다.

numpy
import numpy as np

# Generate a range of dates
daily = np.arange("2024-01-01", "2024-02-01", dtype="datetime64[D]")
# 31 daily dates

monthly = np.arange("2024-01", "2025-01", dtype="datetime64[M]")
# 12 monthly dates

hourly = np.arange("2024-01-01T00", "2024-01-02T00", dtype="datetime64[h]")
# 24 hourly dates

# Resample daily to monthly: take last value of each month
# NumPy itself doesn't have a resample API - use pandas
import pandas as pd
ts = pd.Series(np.random.rand(31), index=daily)
monthly_mean = ts.resample("ME").mean()    # one value per month

# Compute the weekday of each date
weekdays = (daily.astype("datetime64[D]").view("int64") - 4) % 7
# 0 = Monday, ..., 6 = Sunday

# Or use pandas for richer datetime features
pd.DatetimeIndex(daily).day_name()   # ['Monday' 'Tuesday' ...]

Datetime과 Python 상호운용

NumPy datetime64와 Python datetime의 변환은 astype으로 간단합니다. 시간대에 주의하세요. NumPy datetime64는 항상 UTC이며 tz 정보가 없어, tz 인식 pandas Timestamp를 NumPy로 변환하면 tz가 조용히 버려집니다. 시간대를 다루는 작업은 전체를 pandas Timestamp로 쓰세요.

numpy
import numpy as np
import datetime as dt

# NumPy datetime64 -> Python datetime
np_dt = np.datetime64("2024-01-15T10:30:00")
py_dt = np_dt.astype(dt.datetime)   # Python datetime object
# datetime.datetime(2024, 1, 15, 10, 30)

# Python datetime -> NumPy datetime64
np_again = np.datetime64(py_dt)

# Convert a NumPy datetime array to Python datetimes
arr = np.arange("2024-01-01", "2024-01-05", dtype="datetime64[D]")
py_list = arr.astype(dt.datetime).tolist()
# [datetime.date(2024, 1, 1), ...]

# Pandas Timestamp (most flexible)
import pandas as pd
ts = pd.Timestamp("2024-01-15 10:30:00", tz="US/Eastern")
ts.to_numpy()   # converts to UTC datetime64 (tz info dropped!)

# Unix timestamp interconversion
ts_unix = (np_dt - np.datetime64("1970-01-01", "s")) / np.timedelta64(1, "s")
# 1705314600.0   (seconds since Unix epoch)
back = np.datetime64(int(ts_unix), "s").astype("datetime64[s]") + \
       np.timedelta64(int((ts_unix % 1) * 1e9), "ns")

실무의 Datetime

NumPy의 날짜 산술은 빠르지만 제한적입니다. 그룹핑, 리샘플링, 시간대 처리에는 pandas가 맞는 도구입니다. 연중 일수 계산 예시는 NumPy가 강요하는 저수준 날짜 요술을 보여 주며, pandas의 DatetimeIndex.dayofyear는 한 번의 호출로 이를 합니다. 저장과 단순 산술은 NumPy datetime64, 분석은 pandas를 쓰세요.

numpy
import numpy as np

# Compute age in years from birthdates
birthdays = np.array(["1990-05-15", "1985-11-20", "2000-03-10"],
                     dtype="datetime64[D]")
today = np.datetime64("today", "D")
ages_days = (today - birthdays).astype("timedelta64[D]")
ages_years = (ages_days / 365.25).astype(int)
# array([33, 38, 24]) approximately

# Find dates within a window
dates = np.arange("2024-01-01", "2024-06-01", dtype="datetime64[D]")
mask = (dates >= "2024-02-01") & (dates < "2024-03-01")
february = dates[mask]   # all February dates

# Compute day of year
jan1 = dates.astype("datetime64[Y]").astype("datetime64[D]")
# Hmm, this loses month/day; instead:
day_of_year = (dates - dates.astype("datetime64[M]") \
               .astype("datetime64[D]") + 1).astype(int)

# Group by month (manual; pandas is easier)
months = dates.astype("datetime64[M]")
unique_months = np.unique(months)
for m in unique_months:
    mask = months == m
    print(m, dates[mask].size, "days")
13

문자열 연산

벡터화 문자열 연산 (np.char)

np.char는 Python str 메서드의 벡터화 버전을 제공하며 문자열 배열에 요소별로 동작합니다. 새 배열을 반환합니다(NumPy에서 문자열은 불변). 더 정교한 문자열 처리(정규식 추출, 조건 로직)에는 pandas의 .str 접근자가 훨씬 유능하고 인체공학적이므로 실제 데이터 정리 작업에는 이를 선호하세요.

numpy
import numpy as np
names = np.array(["Alice", "Bob", "Carol", "dave"])

# np.char module: vectorized string operations
np.char.upper(names)      # ['ALICE' 'BOB' 'CAROL' 'DAVE']
np.char.lower(names)      # ['alice' 'bob' 'carol' 'dave']
np.char.title(names)      # ['Alice' 'Bob' 'Carol' 'Dave']
np.char.capitalize(names)
np.char.swapcase(names)

# Strip whitespace
s = np.array(["  hello  ", "world  "])
np.char.strip(s)          # ['hello' 'world']
np.char.lstrip(s)
np.char.rstrip(s)

# Splitting and joining
np.char.split(np.array(["a,b,c", "d,e,f"]), sep=",")
# [list(['a', 'b', 'c']) list(['d', 'e', 'f'])]

np.char.join("-", np.array(["abc", "def"]))
# ['a-b-c' 'd-e-f']

# Replace
np.char.replace(np.array(["foo bar", "baz foo"]), "foo", "XXX")
# ['XXX bar' 'baz XXX']

문자열 비교와 검색

np.char에는 벡터화된 문자열 비교, 검색, 길이 함수가 있습니다. find는 찾지 못하면 False가 아니라 -1을 반환하므로 >= 0으로 검사하세요. 정규식 기반 검색과 추출에는 regex=True를 준 pandas의 .str.contains/.str.extract을 쓰세요. np.char의 정규식 지원은 제한적이고 버전 간 일관성이 없습니다.

numpy
import numpy as np
words = np.array(["apple", "banana", "cherry", "date"])

# Element-wise comparison
np.char.equal(words, "apple")        # [ True False False False]
np.char.not_equal(words, "apple")

# Lexicographic comparison
np.char.greater(words, "c")          # [False False  True  True]

# Substring search
np.char.find(words, "a")             # index of 'a', -1 if not found
np.char.count(np.array(["banana", "apple"]), "a")
# [3 1]

# Startswith / endswith
np.char.startswith(words, "a")       # [ True False False False]
np.char.endswith(words, "e")         # [ True False False  True]

# Contains (regex-capable in newer versions)
np.char.find(words, "er") >= 0       # [False False  True False]

# String length
np.char.str_len(words)               # [5 6 6 4]

문자열 연결과 서식

np.char의 문자열 연결은 요소별이며 Python의 + 연산자만큼 편하지 않습니다. 구분자로 합치려 np.char.add 호출을 사슬로 잇거나 np.core.defchararray.add를 써야 합니다. 대부분의 문자열 서식 작업에는 리스트 컴프리헨션이나 pandas의 .str.cat이 np.char보다 명확합니다. np.char.mod는 배치 문자열 생성을 위한 %-서식을 지원합니다.

numpy
import numpy as np
first = np.array(["Alice", "Bob", "Carol"])
last = np.array(["Smith", "Jones", "Brown"])

# Element-wise concatenation
np.char.add(first, last)              # ['AliceSmith' 'BobJones' 'CarolBrown']
np.char.add(first, " " + last)        # nope, this broadcasts weirdly

# Proper way to add a separator
np.char.add(np.char.add(first, " "), last)
# ['Alice Smith' 'Bob Jones' 'Carol Brown']

# Multiply (repeat)
np.char.multiply(np.array(["ab", "cd"]), 3)
# ['ababab' 'cdcdcd']

# Center / ljust / rjust with fill character
np.char.center(np.array(["hi", "yo"]), width=6, fillchar="-")
# ['--hi--' '--yo--']
np.char.rjust(np.array(["1", "12", "123"]), width=5, fillchar="0")
# ['00001' '00012' '00123']

# Format strings
np.char.mod("%05d", np.array([1, 23, 456]))
# ['00001' '00023' '00456']

# Modern Python f-strings don't vectorize - use np.char.mod or list comp
[f"{n:05d}" for n in [1, 23, 456]]   # Python alternative

문자열 dtype과 메모리

NumPy 문자열 dtype은 고정 폭입니다. 'U' = 유니코드(문자당 4바이트), 'S' = ASCII 바이트(문자당 1바이트). 고정 폭보다 긴 문자열은 조용히 잘립니다. 데이터 손실의 흔한 원천입니다. 잘림 없는 가변 길이 문자열은 dtype=object를 쓰세요(느리지만 Python str 객체를 저장). ASCII 데이터에는 'U' 대비 메모리 4배 절약을 위해 'S'를 고르세요.

numpy
import numpy as np

# Fixed-length unicode strings (default)
s = np.array(["hello", "world"])
s.dtype    # dtype('<U5')   <- max length 5 unicode chars

# Fixed-width string dtype (saves memory for ASCII)
s_ascii = np.array(["hello", "world"], dtype="S5")
s_ascii.dtype   # dtype('|S5')  <- bytes, length 5

# If a string exceeds the fixed width, it's truncated
np.array(["abcdef"], dtype="U3")   # ['abc']
np.array(["abcdef"], dtype="S3")   # [b'abc']

# Object dtype for variable-length strings (no truncation, slower)
s_obj = np.array(["a" * 100, "b"], dtype=object)
s_obj.dtype   # dtype('O')

# Convert between unicode and bytes
np.char.encode(np.array(["hello"]), "utf-8")   # array([b'hello'])
np.char.decode(np.array([b"hello"]), "utf-8")  # array(['hello'])

# When loading text data, dtype=None infers per column
# but for strings use U/S for fixed-width or object for variable

실용적 문자열 패턴

return_inverse=True를 준 np.unique가 범주형 문자열을 정수로 인코딩하는(레이블 인코딩) 표준 방법입니다. 원-핫 인코딩은 pandas.get_dummies나 sklearn의 OneHotEncoder를 쓰세요. 숫자를 문자열로 0 패딩하면 파일명 정렬이 사전순이 됩니다(문자열로는 '10' < '2'지만 '010' > '002'). 여러 치환의 임시방편은 np.char.replace 사슬입니다.

numpy
import numpy as np

# Build a categorical label array
labels = np.array(["cat", "dog", "cat", "bird", "dog"])

# Encode strings to integers
unique, encoded = np.unique(labels, return_inverse=True)
print(unique)     # ['bird' 'cat' 'dog']
print(encoded)    # [1 2 1 0 2]   integer codes

# Decode integers back to strings
labels_back = unique[encoded]
# ['cat' 'dog' 'cat' 'bird' 'dog']

# Filter rows of a 2-D array by a string column
data = np.array([["Alice", "30"], ["Bob", "25"], ["Carol", "35"]])
mask = np.char.startswith(data[:, 0], "A")
data[mask]   # [['Alice' '30']]

# Pad numbers as zero-padded strings (for sorting filenames)
nums = np.array([1, 10, 100, 2])
padded = np.char.zfill(nums.astype(str), 3)
# ['001' '010' '100' '002']   now sorts lexicographically

# Compute a sorted argsort using string keys
keys = np.array(["banana", "apple", "cherry"])
order = np.argsort(keys)
keys[order]   # ['apple' 'banana' 'cherry']

# Replace multiple patterns (must chain - no vectorized replace-all)
arr = np.array(["a-b", "c_d", "e.f"])
for ch in ["-", "_", "."]:
    arr = np.char.replace(arr, ch, " ")
print(arr)   # ['a b' 'c d' 'e f']
14

성능과 벡터화

벡터화 vs 루프

NumPy 성능의 단일 최중요 규칙: 배열 요소를 도는 Python 루프를 피하세요. 각 반복마다 Python 인터프리터 오버헤드가 들지만 벡터화된 NumPy 연산은 연속 메모리 위의 단일 C 호출로 실행됩니다. 50~100배 가속이 전형입니다. 루프를 쓰기 전에 물으세요. '이걸 하는 ufunc, 축소, broadcasting 트릭이 있는가?'

numpy
import numpy as np
import time

# BAD: Python loop (slow)
def slow_sum(arr):
    total = 0
    for x in arr:
        total += x
    return total

# GOOD: NumPy reduction (vectorized)
def fast_sum(arr):
    return arr.sum()

big = np.arange(10_000_000)

start = time.perf_counter()
slow_sum(big)
print("loop:", time.perf_counter() - start)   # ~0.6s

start = time.perf_counter()
fast_sum(big)
print("numpy:", time.perf_counter() - start)  # ~0.005s   ~100x faster

# Rule of thumb: if you're writing a for loop over array elements,
# there's probably a vectorized NumPy operation that's 50-100x faster.
# Look for: reductions (sum, mean, max), ufuncs, broadcasting, einsum.

텐서 수축을 위한 np.einsum

einsum은 NumPy에서 가장 유연한 텐서 연산입니다. 하나의 문법이 matmul, 전치, trace, 대각선, 합, 외적, 배칭 연산, 임의 텐서 수축을 처리합니다. 문자열이 입력과 출력 축을 지정하며 합산된 축은 사라집니다. 중간 메모리 폭발을 피하려 수축 사슬에 optimize=True를 쓰세요. 표기법은 연습이 필요하지만 보상이 큽니다.

numpy
import numpy as np

# einsum: Einstein summation - the Swiss Army knife of tensor ops
A = np.random.rand(3, 4)
B = np.random.rand(4, 5)

# Matrix multiplication: C[i,k] = sum_j A[i,j] * B[j,k]
C = np.einsum("ij,jk->ik", A, B)   # same as A @ B

# Transpose
np.einsum("ij->ji", A)             # A.T

# Sum all elements
np.einsum("ij->", A)               # A.sum()

# Sum along an axis
np.einsum("ij->i", A)              # A.sum(axis=1)
np.einsum("ij->j", A)              # A.sum(axis=0)

# Row-wise dot product with a vector
v = np.random.rand(4)
np.einsum("ij,j->i", A, v)         # A @ v

# Outer product
a = np.random.rand(3)
b = np.random.rand(4)
np.einsum("i,j->ij", a, b)         # np.outer(a, b)

# Batched matrix multiply
X = np.random.rand(10, 3, 4)
Y = np.random.rand(10, 4, 5)
np.einsum("bij,bjk->bik", X, Y)    # batched matmul

# optimize=True lets einsum choose a better evaluation order
np.einsum("ij,jk,kl->il", A, B, A.T, optimize=True)

out=과 뷰로 복사 피하기

out=으로 출력 버퍼를 미리 할당하면 핫 루프의 반복 할당을 피합니다. 반복 연산에서 큰 이득입니다. 제자리 연산자(+=, *=)도 임시 객체를 피합니다. reshape과 transpose는 뷰를 반환하지만(복사 없음) fancy 인덱싱과 불리언 마스크는 항상 복사합니다. ascontiguousarray는 필요할 때만 복사하므로 방어적으로 호출해도 안전합니다.

numpy
import numpy as np
import time

# Many ufuncs accept out= to write into an existing buffer (no allocation)
a = np.arange(1_000_000)
out = np.empty(1_000_000)

# Slow: creates a new array
start = time.perf_counter()
b = np.sin(a)
print("alloc:", time.perf_counter() - start)

# Fast: reuses the existing buffer
start = time.perf_counter()
np.sin(a, out=out)
print("reuse:", time.perf_counter() - start)   # faster, no allocation

# In-place operations also avoid copies
a += 10            # in-place add (no temp array)
a *= 2             # in-place multiply
np.sqrt(a, out=a)  # in-place sqrt

# Views vs copies
b = a.reshape(-1, 1000)        # view, no copy
c = a[a > 0.5]                  # copy (fancy indexing)
d = a.transpose()               # view (but maybe non-contiguous)

# ascontiguousarray: copy only if needed
e = np.ascontiguousarray(a)     # no copy if already C-contiguous

메모리 배치와 캐시 효율

메모리 배치가 성능에 중요합니다. C 순서 배열은 행이 연속 저장되므로 마지막 축 연산(예: sum(axis=1))이 캐시 친화적입니다. 잘못된 배치는 캐시 미스를 낳아 연산을 5~10배 느리게 합니다. 연산이 C 연속 데이터를 필요로 하는데 입력 배치를 확신할 수 없으면 np.ascontiguousarray를 쓰세요. .strides가 축별 바이트 스텝을 알려 줍니다.

numpy
import numpy as np
import time

# C order (row-major, default): last axis varies fastest
# F order (column-major): first axis varies fastest

# Iterating along the LAST axis is cache-friendly (C order)
a_c = np.zeros((1000, 1000), order="C")
a_f = np.zeros((1000, 1000), order="F")

# Sum along rows (axis 1): fast for C-order (contiguous in memory)
start = time.perf_counter()
a_c.sum(axis=1)
print("C order, axis=1:", time.perf_counter() - start)

start = time.perf_counter()
a_f.sum(axis=1)
print("F order, axis=1:", time.perf_counter() - start)   # slower

# Rule: for C-order arrays, the last axis is contiguous.
# Iterating a[..., i] is fast; iterating a[i, ...] is slow.

# Force a particular layout (copies only if necessary)
a_c2 = np.ascontiguousarray(a_f)   # now C-contiguous
a_f2 = np.asfortranarray(a_c)      # now F-contiguous

# Check layout
a_c.flags["C_CONTIGUOUS"]    # True
a_c.flags["F_CONTIGUOUS"]    # False

# Strides: bytes to step along each axis
a_c.strides    # (8000, 8)   - 8 bytes per float, 1000 per row
a_f.strides    # (8, 8000)   - first axis is contiguous

프로파일링과 벤치마킹

벤치마킹에는 timeit(Jupyter에서는 %timeit)을 쓰고 노이즈를 제외하려 여러 실행의 최솟값을 취하세요. 더 큰 코드에서는 cProfile과 line_profiler가 실제 병목을 찾아 줍니다. 추측하지 마세요. np.show_config가 NumPy가 MKL/OpenBLAS를 쓰는지 보여 줍니다. 작은 배열에서는 스레드 시작 오버헤드 때문에 단일 스레드가 오히려 빠를 수 있으니 OMP_NUM_THREADS로 실험하세요.

numpy
import numpy as np
import time

# Quick micro-benchmark
def bench(fn, *args, repeat=5):
    times = []
    for _ in range(repeat):
        start = time.perf_counter()
        fn(*args)
        times.append(time.perf_counter() - start)
    return min(times)

a = np.random.rand(1000, 1000)
print("sum axis=0:", bench(lambda x: x.sum(axis=0), a))
print("sum axis=1:", bench(lambda x: x.sum(axis=1), a))

# Memory profiling: check array size
print(f"size: {a.size} elements")
print(f"memory: {a.nbytes / 1e6:.1f} MB")

# Time individual lines with %timeit (in IPython/Jupyter)
# %timeit a.sum()
# %timeit np.einsum("ij->", a)
# %prun my_function()    # line-by-line profiling

# Find bottlenecks with cProfile
import cProfile
cProfile.run("a @ a", sort="cumtime")

# Check if BLAS is using multiple threads
np.show_config()    # shows BLAS/LAPACK info

# Control thread count (sometimes single-thread is faster for small arrays)
import os
os.environ["OMP_NUM_THREADS"] = "4"
os.environ["MKL_NUM_THREADS"] = "4"
15

FFT와 신호 처리

1차원 FFT 기본

np.fft.fft가 이산 푸리에 변환을 계산해 시간 영역 신호를 주파수 영역으로 바꿉니다. 실수 입력에서 스펙트럼은 대칭이며 앞 절반만 고유 정보를 담습니다. fftfreq가 bin 주파수를 반환하며 표본률이 1/dt일 때 나이퀴스트 주파수는 1/(2*dt)입니다. 크기가 각 주파수 성분의 강도를 보여 줍니다.

numpy
import numpy as np

# Generate a signal: two sine waves + noise
t = np.linspace(0, 1, 500, endpoint=False)
signal = np.sin(2 * np.pi * 5 * t) + 0.5 * np.sin(2 * np.pi * 20 * t)
signal += 0.2 * np.random.default_rng(42).standard_normal(500)

# Compute the FFT
fft_vals = np.fft.fft(signal)
# Complex array: magnitude = amplitude, phase = angle

# Frequencies corresponding to each FFT bin
freqs = np.fft.fftfreq(len(signal), d=t[1] - t[0])

# Magnitude spectrum (absolute value)
magnitude = np.abs(fft_vals)

# Power spectral density
power = magnitude ** 2

# Plot the spectrum (only positive frequencies for real signals)
import matplotlib.pyplot as plt
plt.plot(freqs[:len(freqs)//2], magnitude[:len(freqs)//2])
plt.xlabel("Frequency (Hz)")
plt.ylabel("Magnitude")

역 FFT와 재구성

ifft가 fft를 되돌립니다. 왕복(fft 후 ifft)은 (부동소수점 오차까지) 원래 신호를 회복합니다. 반전 전에 스펙트럼을 편집하는 것이 주파수 영역 필터링의 기초입니다. 제거하려는 bin을 0으로 만드세요(로우패스, 하이패스, 밴드패스). 실수 신호에는 rfft/irfft가 스펙트럼의 비음수 절반만 저장해 더 효율적입니다.

numpy
import numpy as np

# Original signal
t = np.linspace(0, 1, 500, endpoint=False)
signal = np.sin(2 * np.pi * 5 * t) + 0.5 * np.sin(2 * np.pi * 20 * t)

# Forward FFT
fft_vals = np.fft.fft(signal)

# Inverse FFT reconstructs the original signal
reconstructed = np.fft.ifft(fft_vals)
np.allclose(signal, reconstructed.real)   # True

# Modify the spectrum (e.g. zero out high frequencies) then invert
fft_filtered = fft_vals.copy()
freqs = np.fft.fftfreq(len(signal), d=t[1] - t[0])
fft_filtered[np.abs(freqs) > 10] = 0   # low-pass filter

filtered_signal = np.fft.ifft(fft_filtered).real
# Now only the 5 Hz component remains; the 20 Hz is removed

# rfft / irfft: optimized for real input (half the storage)
rfft_vals = np.fft.rfft(signal)   # only non-negative frequencies
reconstructed2 = np.fft.irfft(rfft_vals, n=len(signal))

2차원 FFT (이미지 처리)

fft2 / ifft2가 이미지 처리의 2차원 등가물입니다. fftshift가 영주파수 성분을 배열 중앙으로 옮기며(시각화와 필터링의 자연스러운 관례) 이동된 스펙트럼의 중앙 로우패스 마스크가 이미지를 흐리게 하고, 하이패스(반전 마스크)는 모서리를 선명하게 합니다. 공간 영역의 합성곱은 주파수 영역의 곱과 같아 큰 커널에서 크게 빨라집니다.

numpy
import numpy as np

# 2-D FFT for image processing
image = np.random.rand(64, 64)   # treat as a grayscale image

# Forward 2-D FFT
fft2d = np.fft.fft2(image)

# Shift zero frequency to the center (standard convention)
fft2d_shifted = np.fft.fftshift(fft2d)

# Magnitude spectrum (log-scaled for visualization)
magnitude = np.log(np.abs(fft2d_shifted) + 1)

# Inverse: unshift then ifft2
fft2d_unshifted = np.fft.ifftshift(fft2d_shifted)
reconstructed = np.fft.ifft2(fft2d_unshifted).real
np.allclose(image, reconstructed)   # True

# Low-pass filter: keep only central low frequencies
rows, cols = image.shape
crow, ccol = rows // 2, cols // 2
mask = np.zeros((rows, cols), dtype=bool)
mask[crow-10:crow+10, ccol-10:ccol+10] = True   # central 20x20 block
fft2d_shifted[~mask] = 0
blurred = np.fft.ifft2(np.fft.ifftshift(fft2d_shifted)).real

윈도우 함수와 스펙트럼 누설

신호의 유한 조각을 FFT하면 스펙트럼 누설이 생깁니다. 진짜 주파수의 에너지가 인접 bin으로 '새는' 것입니다. 윈도우 함수(Hann, Hamming, Blackman)는 신호를 가장자리에서 매끄럽게 0으로 줄여 누설을 줄이지만 주파수 피크가 약간 넓어집니다. STFT(스펙트로그램)에서는 50% 겹침의 Hann 윈도우가 완전 재구성의 COLA 속성을 만족합니다.

numpy
import numpy as np

# Applying a window reduces spectral leakage at the edges of the FFT
N = 1024
t = np.linspace(0, 1, N, endpoint=False)
signal = np.sin(2 * np.pi * 50 * t)

# Rectangular window (no window) - lots of leakage
rect_fft = np.abs(np.fft.fft(signal))

# Hann window - smooth taper to zero at both ends
hann = np.hanning(N)
signal_hann = signal * hann
hann_fft = np.abs(np.fft.fft(signal_hann))

# Other common windows
hamming = np.hamming(N)
blackman = np.blackman(N)
bartlett = np.bartlett(N)

# Compare spectral leakage: Hann has wider main lobe but lower sidelobes
# Trade-off: frequency resolution vs leakage

# For overlap-add processing, use windows that sum to 1 when overlapped:
# Hann at 50% overlap -> COLA (constant overlap-add) property

# Short-time Fourier transform (STFT) via windowed FFTs
def stft(signal, window_size=256, hop=128):
    n_frames = (len(signal) - window_size) // hop + 1
    window = np.hanning(window_size)
    frames = []
    for i in range(n_frames):
        start = i * hop
        frame = signal[start:start + window_size] * window
        frames.append(np.fft.rfft(frame))
    return np.array(frames).T   # shape (n_freqs, n_frames)

FFT를 통한 합성곱

FFT 기반 합성곱은 커널을 슬라이드하는 대신 스펙트럼을 곱합니다. 큰 신호/커널에서 훨씬 빠릅니다(O(N log N) vs O(N*K)). 원형 합성곱 아티팩트를 피하려 합성곱 길이를 최소 N+K-1 이상으로 패딩해야 하며 2의 거듭제곱으로 올리면 FFT가 가장 빠릅니다. scipy.signal.fftconvolve가 프로덕션 준비 버전이므로 직접 만들지 말고 이것을 쓰세요.

numpy
import numpy as np

# Convolution theorem: convolution in time = multiplication in frequency
# For large signals, FFT-based convolution is O(N log N) vs O(N^2) direct

signal = np.random.rand(10000)
kernel = np.random.rand(100)

# Method 1: np.convolve (direct, O(N*K))
direct_conv = np.convolve(signal, kernel, mode="same")

# Method 2: FFT-based convolution (fast for large kernels)
def fft_convolve(signal, kernel):
    n = len(signal) + len(kernel) - 1   # full convolution length
    n_fft = 1 << int(np.ceil(np.log2(n)))   # next power of 2 (faster FFT)
    fft_signal = np.fft.rfft(signal, n_fft)
    fft_kernel = np.fft.rfft(kernel, n_fft)
    fft_conv = fft_signal * fft_kernel
    conv = np.fft.irfft(fft_conv, n_fft)[:n]
    return conv

fft_result = fft_convolve(signal, kernel)
# Trim or pad to match 'same' mode if needed

# scipy.signal.fftconvolve is a production-ready version
from scipy.signal import fftconvolve
scipy_conv = fftconvolve(signal, kernel, mode="same")

# Cross-correlation (flip the kernel first)
xcorr = fftconvolve(signal, kernel[::-1], mode="same")

# Autocorrelation
autocorr = fftconvolve(signal, signal[::-1], mode="same")
16

Masked 배열

Masked 배열 생성

masked 배열은 데이터 자체를 오염시키지 않고(NaN은 float dtype을 강제) 유효하지 않은/결측 항목을 가진 데이터를 표현합니다. 마스크는 병렬 불리언 배열이며 True가 '유효하지 않음, 이 항목 무시'입니다. 흔한 생성자는 masked_equal/masked_where입니다. .filled()는 마스크된 항목을 채움 값으로 바꿔 일반 ndarray로 되돌립니다.

numpy
import numpy as np
import numpy.ma as ma

# A masked array = data + a boolean mask (True = invalid/missing)
data = np.array([1, 2, -999, 4, 5])
mask = np.array([False, False, True, False, False])
m = ma.masked_array(data, mask=mask)
# masked_array(data=[1, 2, --, 4, 5],
#              mask=[False, False,  True, False, False])

# Common constructors
ma.masked_equal(data, -999)        # mask all elements == -999
ma.masked_greater(data, 3)         # mask elements > 3
ma.masked_where(data > 3, data)    # general: mask where condition
ma.masked_invalid([1.0, np.nan, 3.0])   # mask NaN/inf

# Access components
m.data       # the underlying data (including masked values)
m.mask       # the boolean mask
m.filled(0)  # replace masked values with 0, return regular ndarray

# Check if any value is masked
m.mask.any()    # True

Masked 배열 연산

masked 배열의 연산은 마스크를 자동 전파합니다. 마스크된 항목은 결과에서 마스크 상태를 유지하고 축소는 이를 무시합니다. -999 같은 센티널 값을 쓰는 것에 대한 핵심 장점입니다. 모든 계산에서 유효하지 않은 항목을 수동 필터할 필요가 없습니다. 일반 배열이 필요하면 .compressed()가 유효 값만의 평면 ndarray를 반환합니다.

numpy
import numpy as np
import numpy.ma as ma

m = ma.masked_array([1, 2, 3, 4, 5],
                    mask=[False, False, True, False, False])

# Reductions ignore masked values
m.sum()      # 12   (skips the masked 3)
m.mean()     # 3.0  (mean of unmasked only)
m.max()      # 5
m.min()      # 1

# Arithmetic propagates the mask
m + 10       # [11 12 -- 14 15]
m * 2        # [2 4 -- 8 10]

# Combine masks from two masked arrays
m2 = ma.masked_array([10, 20, 30, 40, 50],
                     mask=[True, False, False, False, True])
m + m2       # [-- 22 -- 44 --]   union of masks

# Logical operations
m < 4        # masked_array, masked entries stay masked

# Compress: extract only the unmasked values (returns 1-D array)
m.compressed()   # [1 2 4 5]   (regular ndarray, no mask)

# Count valid entries
ma.count(m)      # 4
m.count()        # 4

채우기와 변환

filled()가 masked 배열을 일반 ndarray로 되돌리는 표준 방법입니다. 채움 값은 다운스트림 코드에 맞추세요(플롯할 실수는 NaN, 정수 배열은 0, 결측 대체는 평균). 주의: np.asarray(masked_array)는 '마스크된 값을 포함한' 기저 데이터를 반환합니다. 변환을 명시하려 항상 먼저 .filled()를 호출하세요.

numpy
import numpy as np
import numpy.ma as ma

m = ma.masked_array([1.0, 2.0, 3.0, 4.0],
                    mask=[False, True, False, True])

# filled(): replace masked entries with a fill value
m.filled(0)         # [1. 0. 3. 0.]   - regular ndarray
m.filled(np.nan)    # [ 1. nan  3. nan]
m.filled(m.mean())  # fill with mean of unmasked

# The default fill value depends on dtype
m.fill_value    # 1e+20 for floats, 999999 for ints, etc.

# Set a custom fill value
m2 = ma.masked_array([1, 2, 3], mask=[0, 1, 0], fill_value=-1)

# Convert to a plain ndarray (loses mask info!)
arr = np.asarray(m)         # includes masked values! [1. 2. 3. 4.]
arr_filled = np.asarray(m.filled(np.nan))   # NaN where masked

# Convert a regular array with sentinel values to masked
data = np.array([1, -999, 3, -999, 5])
m3 = ma.masked_equal(data, -999)

# Convert masked back to array with NaN (for plotting)
arr_nan = ma.filled(m, np.nan)

Masked 배열 인덱싱

masked 배열 인덱싱은 일반 ndarray와 같고 결과에 마스크가 보존됩니다. 위치에 ma.masked를 할당하면 마스크되고, 일반 값을 할당하면 마스크가 해제됩니다. .mask = ma.nomask가 모든 마스크를 지웁니다. .data 속성은 (마스크된 것 포함) 원시 기저 값을 주어 숨겨진 것을 검사할 때 유용합니다.

numpy
import numpy as np
import numpy.ma as ma

m = ma.masked_array(np.arange(12).reshape(3, 4),
                    mask=[[0, 0, 1, 0],
                          [0, 1, 0, 0],
                          [1, 0, 0, 0]])

# Indexing works like regular arrays
m[0]            # first row (mask preserved)
m[1, 2]         # scalar value (or masked if masked)
m[:, 1]         # column 1

# Boolean mask on top of masked array
m[m.data > 5]   # values > 5 (mask still applied)

# Set values (and unmask)
m[0, 0] = 99
m[0, 0] = ma.masked   # re-mask a specific element

# Reset the mask entirely
m.mask = ma.nomask     # no values masked
m[1, 1] = ma.masked    # mask a single value

# Check element-wise
m[0, 2] is ma.masked   # True if that element is masked

# Logical operations keep the mask
(m > 5).data    # boolean array
(m > 5).mask    # propagated mask

# Iteration skips masked values (kind of)
list(m.compressed())   # all unmasked values, flattened

Masked 배열을 쓸 때

masked 배열이 빛나는 경우: (1) dtype이 정수라 -999 같은 센티널 값을 NaN으로 바꿀 수 없을 때, (2) 마스크에 '육지 vs 바다'나 '저품질 측정' 같은 도메인 의미가 있을 때, (3) 값과 별도로 유효성을 추적해야 할 때. 순수 NaN 기반 결측 데이터에는 nan* 함수가 있는 일반 배열이 더 단순하고 빠릅니다.

numpy
import numpy as np
import numpy.ma as ma

# Scenario 1: Sentinel values in data (e.g. -999 for missing)
temps = np.array([23.5, -999, 24.0, -999, 22.5])
m = ma.masked_equal(temps, -999)
m.mean()   # 23.33...  (ignores -999 entries)

# Scenario 2: Quality flags / validity
values = np.array([10, 12, 8, 15, 11])
quality = np.array([1, 1, 0, 1, 0])   # 0 = bad
m = ma.masked_array(values, mask=(quality == 0))
m.mean()   # (10 + 12 + 15) / 3 = 12.33

# Scenario 3: Grid data with land/sea mask
sst = np.random.rand(5, 5) * 30   # sea surface temperature
land_mask = np.array([
    [1, 1, 0, 0, 0],
    [1, 0, 0, 0, 1],
    [0, 0, 1, 0, 0],
    [0, 1, 0, 0, 1],
    [1, 0, 0, 1, 1],
], dtype=bool)
sst_masked = ma.masked_array(sst, mask=land_mask)
sst_masked.mean()   # average over ocean only

# When NOT to use: if you just have NaN, regular arrays work fine
# (and np.nanmean etc. handle them). Use masked arrays when:
# - You need integer dtype (NaN forces float)
# - You have a non-NaN sentinel (-999, 0, etc.)
# - The mask has semantic meaning (quality flag, region)
17

구조화 배열

구조화 dtype 정의

구조화 dtype은 이질적 레코드형 데이터를 단일 NumPy 배열에 저장하게 합니다. 데이터베이스 테이블처럼. 타입 코드는 <kind><bytes> 형태입니다. i4 = 4바이트 정수, f8 = 8바이트 실수, U20 = 20자 유니코드, ? = 불리언. 각 요소는 필드 이름으로 인덱싱할 수 있는 레코드입니다. C 구조체와의 저수준 상호운용이나 pandas가 없을 때 쓰세요.

numpy
import numpy as np

# Define a structured dtype: list of (name, format) tuples
dt = np.dtype([("name", "U20"),
               ("age", "i4"),
               ("weight", "f8"),
               ("active", "?")])    # ? = bool

# Create an array with this dtype
people = np.array([("Alice", 30, 65.5, True),
                   ("Bob", 25, 80.0, False),
                   ("Carol", 35, 55.0, True)], dtype=dt)

print(people)
# [('Alice', 30, 65.5,  True) ('Bob', 25, 80. , False) ...]

# Each element is a record (tuple-like)
people[0]              # ('Alice', 30, 65.5, True)
people[0]["name"]      # 'Alice'

# Type codes: i1/i2/i4/i8 (ints), u1..u8 (unsigned),
#             f2/f4/f8 (floats), U/n (strings), ? (bool), M8 (datetime)

필드 접근

이름으로 필드에 접근하면(data['age']) 모든 레코드에 걸친 그 컬럼의 '뷰'를 반환합니다. 복사 없음. 다중 필드 접근(data[['name', 'age']])은 오래된 NumPy에서는 복사본이고 NumPy >= 1.16에서는 뷰입니다. 필드 할당은 스칼라(broadcast됨)나 길이가 맞는 배열로 동작합니다. data.dtype.names가 순회용 필드 이름 목록을 줍니다.

numpy
import numpy as np
dt = np.dtype([("name", "U20"), ("age", "i4"), ("score", "f4")])
data = np.array([("Alice", 30, 9.5),
                 ("Bob", 25, 8.0),
                 ("Carol", 35, 9.8)], dtype=dt)

# Access a single field across all records (returns a view)
data["name"]    # ['Alice' 'Bob' 'Carol']
data["age"]     # [30 25 35]
data["age"].mean()   # 30.0

# Modify a field
data["age"] += 1    # increment everyone's age
data["score"] = 0   # set all scores to 0

# Access multiple fields at once
data[["name", "score"]]   # new structured array with just those fields

# Field assignment with another array
data["score"] = [9.5, 8.0, 9.8]

# Iterate records (each record is a tuple)
for rec in data:
    print(rec["name"], rec["age"])

# Iterate fields
for name in data.dtype.names:
    print(name, data[name]

구조화 배열 정렬과 필터링

구조화 배열은 order= 인자로 필드별 정렬합니다. 한 필드는 문자열, 사전식 다중 키 정렬은 문자열 리스트. 필터링은 일반 배열과 같습니다. 필드 비교로 불리언 마스크를 만들고 fancy-index하세요. 대부분의 축소는 필드별로 동작합니다. 더 정교한 group-by/집계는 pandas가 훨씬 쉽지만, 단순한 경우에는 구조화 배열이 가벼운 대안이 될 수 있습니다.

numpy
import numpy as np
dt = np.dtype([("name", "U20"), ("age", "i4"), ("score", "f4")])
data = np.array([("Alice", 30, 9.5),
                 ("Bob", 25, 8.0),
                 ("Carol", 35, 9.8),
                 ("Dave", 28, 7.5)], dtype=dt)

# Sort by a single field
np.sort(data, order="age")         # ascending by age
np.sort(data, order="score")[::-1] # descending by score

# Sort by multiple fields (lexicographic)
np.sort(data, order=["score", "age"])  # primary: score, secondary: age

# argsort with order
idx = np.argsort(data, order="score")
data[idx]   # records sorted by score

# Filter by a field
mask = data["age"] > 28
data[mask]   # Alice, Carol

# Complex conditions
mask = (data["score"] > 8) & (data["age"] < 35)
data[mask]   # Alice

# Find unique values of a field
np.unique(data["age"])   # [25 28 30 35]

# Aggregate per field
data["age"].mean()
data["score"].std()

레코드 배열 (recarray)

레코드 배열(recarray)은 (data['age'] 대신 data.age처럼) 속성 스타일 필드 접근을 약간의 성능 비용으로 제공합니다. 편의는 대체로 미용적이며 내부는 구조화 배열과 같습니다. 대부분의 프로덕션 코드에는 평범한 구조화 배열이 선호되고(더 빠르고 명시적) recarray는 따옴표 타이핑이 거슬리는 대화형 탐색에 편리합니다.

numpy
import numpy as np

# Record arrays: access fields as ATTRIBUTES (data.age vs data["age"])
dt = np.dtype([("name", "U20"), ("age", "i4"), ("score", "f4")])

# Method 1: view as recarray
data = np.array([("Alice", 30, 9.5),
                 ("Bob", 25, 8.0)], dtype=dt).view(np.recarray)

data.name    # ['Alice' 'Bob']   - attribute access!
data.age     # [30 25]
data.age.mean()

# Method 2: create directly with np.rec.array
recs = np.rec.array([("Alice", 30, 9.5),
                     ("Bob", 25, 8.0)],
                    dtype=[("name", "U20"), ("age", "i4"), ("score", "f4")])
recs.name    # attribute access
recs[0].name # 'Alice'

# Trade-off: recarray is slightly slower and uses a bit more memory
# than a plain structured array, but the syntax is cleaner.

# In practice, prefer plain structured arrays for performance,
# recarray only when you really want attribute access (e.g. in REPL).

구조화 배열 vs Pandas

거의 모든 테이블 데이터 분석에는 pandas가 더 낫습니다. NumPy 위에 만들어졌지만 groupby, 조인, 시계열, 결측 데이터 처리, 풍부한 I/O를 더합니다. 구조화 배열이 가치 있는 경우: (1) 메모리가 빠듯할 때(DataFrame보다 2~10배 작음), (2) 구조체 배치를 기대하는 C/Fortran 코드와의 상호운용, (3) pandas가 없는 환경. pd.DataFrame(arr)과 df.to_records()로 자유롭게 변환하세요.

numpy
import numpy as np
import pandas as pd

# Same data as a structured array vs a pandas DataFrame
dt = np.dtype([("name", "U20"), ("age", "i4"), ("score", "f4")])
sa = np.array([("Alice", 30, 9.5),
               ("Bob", 25, 8.0),
               ("Carol", 35, 9.8)], dtype=dt)

df = pd.DataFrame(sa)   # easy conversion
#    name  age  score
# 0  Alice   30    9.5
# 1    Bob   25    8.0
# 2  Carol   35    9.8

# Conversion back
sa2 = df.to_records(index=False)

# When to use structured arrays (NumPy):
# - Memory is tight (no pandas overhead, ~2-10x smaller)
# - Interoperating with C/Fortran code that expects structs
# - Simple, fixed-schema numeric data
# - Embedded / scientific computing without pandas available

# When to use pandas:
# - Heterogeneous data with mixed types
# - Need groupby, join, resample, time series
# - Handling missing data (NaN handling is richer)
# - Reading/writing CSV, Excel, SQL, Parquet
# - Most data analysis workflows

# Pandas is built on top of NumPy - usually the better default.
# Structured arrays are a low-level escape hatch.
18

고급 einsum과 Stride 트릭

einsum 패턴 치트시트

einsum은 하나의 일관된 문법으로 방대한 연산을 커버합니다. 행렬 곱, 전치, trace, 대각선, 합, 외적, 배칭 연산, 임의 텐서 수축. 규칙: 각 입력에 축 레이블 문자열을 주고, 출력은 유지할 레이블을 갖으며, 입력에는 있지만 출력에는 없는 레이블은 합산됩니다. 이것을 익히면 대부분의 선형 대수를 한 줄로 표현할 수 있습니다.

numpy
import numpy as np
A = np.random.rand(3, 4)
B = np.random.rand(4, 5)
v = np.random.rand(4)

# Matrix multiply
np.einsum("ij,jk->ik", A, B)   # = A @ B

# Matrix-vector multiply
np.einsum("ij,j->i", A, v)     # = A @ v

# Vector inner product (dot)
np.einsum("i,i->", v, v)       # = v @ v = sum(v**2)

# Outer product
np.einsum("i,j->ij", v, v)     # = np.outer(v, v)

# Trace
np.einsum("ii->", A) if A.shape[0] == A.shape[1] else None

# Diagonal
M = np.random.rand(5, 5)
np.einsum("ii->i", M)          # = np.diag(M)

# Transpose
np.einsum("ij->ji", A)         # = A.T

# Sum all elements
np.einsum("ij->", A)           # = A.sum()

# Sum along axis 0
np.einsum("ij->j", A)          # = A.sum(axis=0)

# Element-wise (Hadamard) product
np.einsum("ij,ij->ij", A, A)   # = A * A

# Batched matrix multiply
X = np.random.rand(10, 3, 4)
Y = np.random.rand(10, 4, 5)
np.einsum("bij,bjk->bik", X, Y)   # batched A @ B

Strides와 as_strided

as_strided는 임의 stride의 뷰를 만들어 데이터 복사 없이 슬라이딩 윈도우, 롤링 통계, 다른 '가상' 배열을 구현하게 합니다. 위험합니다. 잘못된 stride는 범위 밖 메모리를 읽을 수 있습니다(조용한 손상 또는 크래시). stride를 올바르게 계산하는 안전한 sliding_window_view(NumPy >= 1.20)를 선호하세요. as_strided는 sliding_window_view가 사용 사례에 안 맞을 때만 쓰세요.

numpy
import numpy as np

# np.lib.stride_tricks.as_strided: create views with custom strides
# Extremely powerful but DANGEROUS - can read out-of-bounds memory

a = np.arange(10)
print(a.strides)   # (8,)   - 8 bytes per int64

# Create a sliding-window view WITHOUT copying data
from numpy.lib.stride_tricks import sliding_window_view, as_strided

# Modern, safe way (NumPy >= 1.20):
windows = sliding_window_view(a, 3)
# shape (8, 3): [[0,1,2], [1,2,3], ..., [7,8,9]]
# This is a VIEW - shares memory with a

# Compute moving average using sliding windows
data = np.random.rand(1000)
window = 5
ma = sliding_window_view(data, window).mean(axis=1)
# shape (996,) - moving average

# The low-level (DANGEROUS) as_strided
# shape = (8, 3), strides = (8, 8)  -> step 1 element along both axes
windows2 = as_strided(a, shape=(8, 3), strides=(8, 8))
# Same as sliding_window_view(a, 3) but you must compute shape/strides
# yourself - get it wrong and you read garbage or crash.

# ALWAYS prefer sliding_window_view - it computes strides safely.

슬라이딩 윈도우와 롤링 연산

sliding_window_view는 데이터 복사 '없이' 윈도우의 가상 배열을 만들어 롤링 계산에 극히 메모리 효율적입니다. 롤링 통계에는 .mean(axis=1) / .max(axis=1)을 쓰세요. 2차원 이미지에서 (3, 3) 윈도우 형상은 끝에 (..., 3, 3) 형상의 패치를 만들며 마지막 두 축으로 축소하면 흐림/합성곱 효과가 됩니다. strided 윈도우는 결과를 [::stride]로 슬라이스하세요.

numpy
import numpy as np
from numpy.lib.stride_tricks import sliding_window_view

# 1-D rolling window
data = np.arange(10)
windows = sliding_window_view(data, 4)
# shape (7, 4): [[0,1,2,3], [1,2,3,4], ..., [6,7,8,9]]

# Rolling mean (window=4)
rolling_mean = windows.mean(axis=1)
# [1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5]

# Rolling max / min / sum
rolling_max = windows.max(axis=1)
rolling_min = windows.min(axis=1)
rolling_sum = windows.sum(axis=1)

# 2-D sliding window (e.g. for image processing)
img = np.random.rand(10, 10)
patches = sliding_window_view(img, (3, 3))
# shape (8, 8, 3, 3): each (i,j) is a 3x3 patch centered around (i+1, j+1)

# Compute patch-wise mean (blur effect)
blurred = patches.mean(axis=(-2, -1))
# shape (8, 8)

# Convolution-like operation (no padding, stride 1)
kernel = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])
convolved = (patches * kernel).sum(axis=(-2, -1))

# Window with step (downsample): slice the windows
windowed_stride2 = sliding_window_view(data, 4)[::2]
# shape (4, 4)

broadcast_arrays와 Tile 트릭

broadcast_to와 broadcast_arrays는 데이터 복사 0으로 가상 broadcast 뷰를 만들어 메모리 효율적 코드에 유용합니다. ogrid는 결합 시 전체 격자로 broadcasting되는 개방형(1차원) 벡터를 만들어, 밀집 격자를 만드는 meshgrid보다 메모리를 아낍니다. meshgrid가 메모리를 폭발시킬 큰 격자 계산에는 ogrid, 밀집 등가물(인덱싱에 편리)에는 mgrid를 쓰세요.

numpy
import numpy as np
from numpy.lib.stride_tricks import broadcast_arrays, broadcast_to

# broadcast_to: view of an array broadcast to a new shape (read-only)
a = np.array([1, 2, 3])
b = np.broadcast_to(a, (4, 3))
# shape (4, 3), all rows = [1, 2, 3], no data copied
# b[0, 0] = 99   # ERROR - read-only

# broadcast_arrays: broadcast several arrays together (as views)
x = np.array([1, 2, 3])           # (3,)
y = np.array([[10], [20]])        # (2, 1)
bx, by = broadcast_arrays(x, y)
bx.shape   # (2, 3)
by.shape   # (2, 3)
# bx, by share memory with x, y (just with new strides)

# Use case: build coordinate grids without copying
xs = np.array([0, 1, 2])
ys = np.array([0, 1, 2, 3])
X, Y = np.meshgrid(xs, ys)        # creates copies
X2, Y2 = broadcast_arrays(xs, ys) # views - no copies!
# X2, Y2 are read-only views

# ogrid / mgrid: open / dense meshgrids
ox, oy = np.ogrid[0:3, 0:4]       # column + row vectors (views)
ox.shape   # (3, 1)
oy.shape   # (1, 4)
# Use for broadcasting computations: X = ox + oy  (shape (3, 4))

mx, my = np.mgrid[0:3, 0:4]       # dense (copies), shape (3, 4) each

메모리 효율 뷰를 위한 커스텀 Strides

축에 stride 0을 준 as_strided는 데이터 복사 없이 그 축을 따라 배열을 가상으로 타일링합니다. 쌍별 거리 예시가 패턴을 보여 줍니다. as_strided로 크기 1의 축을 삽입해 broadcasting이 입력을 미리 복사하지 않고 전체 차이 행렬을 만들게 합니다. 고급이고 위험합니다. 항상 형상/stride를 신중히 검증하고 메모리가 정말 빠듯할 때만 as_strided를 선호하세요.

numpy
import numpy as np
from numpy.lib.stride_tricks import as_strided

# Use case: compute pairwise distances without forming the full matrix
# (still O(N^2) compute, but at least no extra copy of the data)
points = np.random.rand(1000, 3)   # 1000 points in 3-D

# Method 1: explicit broadcasting (creates intermediates)
# diff = points[:, None, :] - points[None, :, :]   # (1000, 1000, 3) = 24MB
# dists = np.linalg.norm(diff, axis=-1)            # (1000, 1000)

# Method 2: use as_strided to view points as (1000, 1, 3) and (1, 1000, 3)
# without copying - same compute, less peak memory
n, d = points.shape
p1 = as_strided(points, shape=(n, 1, d),
                strides=(points.strides[0], 0, points.strides[1]))
p2 = as_strided(points, shape=(1, n, d),
                strides=(0, points.strides[0], points.strides[1]))
# p1 and p2 share memory with points (zero-copy broadcast views)
# diff = p1 - p2  still allocates (n, n, d), but the inputs didn't

# Compute a Gram matrix (X @ X.T) with as_strided
X = np.random.rand(100, 5)
gram = np.einsum("ij,ik->jk", X, X)   # = X.T @ X, shape (5, 5)

# Tile an array virtually (without copying)
a = np.array([1, 2, 3])
tiled_view = as_strided(a, shape=(4, 3),
                        strides=(0, a.strides[0]))
# Each row is [1, 2, 3], no data copied

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.