본문 바로가기
Programming Language/Python

Numpy

by hleej 2026. 1. 17.

 Obdisian에 정리한 markdownhtml export한 뒤, Tistory로 옮긴 게시글.

 last update : 2026-01-19

Numpy

Numerical Python
행렬이나 다차원 배열을 쉽게 처리할 수 있게 해주는 라이브러리이다.
Numpy Document

import numpy as np

특징
C로 구현되어 연속적인 메모리에 저장되어 아주 빠르다. (python의 List는 pointer 배열이다)
하지만 그때문에 한번에 한가지의 자료형만 저장할 수 있고, 배열의 크기를 바꿀 때 cost가 크다.


Syntax

[ np.ndarray ]

N-dimentional Array

다차원 배열

(동일한 type)

의 데이터를 빠르고 효율적으로 계산할 수 있는 객체이다.
tensor: 수학적으로 numerical array를 의미한다.

Generate ndarray / Identity, Zeros, Ones, Full / Copy

#==== Generate =======================
# list => ndarray
arr = np.array([0, 1, 2, 3]) # np.array(list {, dtype=})
# ndarray => list
l = arr.tolist() # print 1 line regradless to dim.

arr2 = np.arange(4) # [0, 1, 2, 3]
arr2 = np.arange(2, 6, 2) # arange(from, to, step) [from, to)

arr3 = np.ndarray((4,), np.int64) # Just reserve memory
arr3[:] = [0, 1, 2, 3]

arr4 = np.linspace(0., 10., num=5) # generate arithmetic sequence starts with 0 to 10. array([ 0. ,  2.5,  5. ,  7.5, 10. ])

#==== Identity, Zero, One, Full Matrix =======================
arr = np.eye(3) # returns 3x3 Identity Matrix (float)
arr = diag([4, 5, 6]) # returns 3x3 diagnoal matrix. 456 is singular value. (int)

arr = np.zeros((2, 3)) # returns 2x3 Matrix filled with 0 (float)
arr = np.ones((2, 3)) # returns 2x3 Matrix filled with 1 (float)
arr = np.full((2, 3), a) # returns 2x3 Matrix filled with a (type(a))

arr2 = np.zeros_like(arr) # returns Matrix shaped like arr filled with 0 (dtype(arr)) 

#==== Copy =======================
arr_alias = arr
arr_orig = np.copy(arr) # deep copy

Dimension / Shape / Type

#==== Shape =======================
print(np.array([1, 2, 3]).shape) # (3, )
print(np.array([[1, 2, 3], [2, 3, 4]]).shape) # (2, 3) (ROW/COL)

print(arr.ndim) # 2. Number of Dimension
print(arr.size) # 10

print(arr.expand_dims(arr, axis=2)) # expand dim

#==== Change Shape =======================
print(arr.flatten()) # reshape arr into 1 Dim. Not Change original
print(arr.ravel()) # Same as above. Change original
arr.reshape(-1) # Same as above. NOT Change original
arr.reshape(2, -1) # 2X3(auto)
arr.reshape(3, 2) # 3X2


#==== Type =======================	
print(type(arr)) # <class 'numpy.ndarray'>
print(arr.dtype) # np.int32

#==== Change Type =======================
arrFloat = arr.astype(np.float32) # assign ndarray type to float
# np.int8      np.int16     np.int32
# np.uint8     np.uint16    np.uint32
# np.float16   np.float32   np.float64   np.float128
# np.bool_
# str 

Indexing & Slicing / Fancy Indexing / Boolean Indexing

#==== Indexing & Slicing =======================
arr = np.arange(9).reshape(3, 3)
# Indexing
arrRow = arr[0] # first ROW of arr
arrLastRow = arr[-1] # last ROW of arr
number = arr[1, 2] # same as `arr[1][2]`, but much faster
arr[-1, -1] # lower right element of matrix

# Slicing (alias)
arrRows = arr[1:3] # second, third ROWs of arr
arr = arr[:-1] # [[0, 1, 2], [3, 4, 5]]. [-a, -b)
arrCol = arr[:, 0] # first COL of arr
arrCol2 = arr[:, :2] # 0-1 COL of arr


#==== Fancy Indexing =======================
# []를 통해 axis별로 원하는 index만 pick할 수 있다. 
arr = np.arange(16).reshape(4, 4)
arr2 = arr[[1, 3]] # arr[[1, :], [3, :]]
arr3 = arr[[1, 3], 2] # arr[[1, 2], [3, 2]]
arr4 = arr[[1, 3], 1:3] # arr[[1, 1:3], [3, 1:3]] 

#==== Boolean Indexing (Boolean Mask) =======================
arr = np.arange(6).reshape(2, 3)
print(arr > 1) # Boolean Mask
# [[False False  True]
#  [ True  True  True]]
print(arr[arr > 1]) 
# [2 3 4 5]

complex_mask = arr[(1 < arr) & (arr < 5)]

Sort / Argsort

arr = np.array([5, 3, 1, 2, 4])
#==== Sort =======================
# np.sort() : 원본 수정 X
arr_sort = np.sort(arr) # default `axis=-1`(마지막 축)
arr_sort = np.sort(arr, axis=0) # 각 Row에 대해 sort(ROW)
arr_sort = np.sort(arr)[::-1] # 내림차순 정렬

# ndarray.sort() : 원본 수정 O
arr.sort() # returns None

#==== ArgSort =======================
# 학생 이름 names = [...], 학생 성적 scores = [...]이 있을 때, 성적에 따른 학생 이름을 출력한다던가.
arr_sort = np.argsort(arr) # [2 3 1 4 0]. 정렬 시 index를 반환.

Unique / Where

arr = np.array([1, 2, 2, 3, 4])

np.unique(arr) # returns arr without overlapped values
np.where(arr < 2) # returns index like ([axis 0 indexes], [axis 1 indexes], ...)
np.where(arr > 5, 1, 0) # if elements of arr is greater than 5, TRUE: 1, FALSE: 0
np.where(arr < 2, arr2, arr3) # Broadcast element with arr2 or arr3 (same position)

Concatenate / Stack / Split

np.concatenate((arr1, arr2), axis=0) # returns Concatenate 2 Matrixs same shape. 
np.stack((arr1, arr2), axis=2) # returns Stack 2 Matrix on NEW given dimension.
np.split(arr, 3, axis=0) # returns 3 split matrix with given axis

Flip / Rotate

arr = np.arange(9).reshape((3, 3))
#==== Flip =======================
arrFlipLR = np.fliplr(arr) # flip x (Left to Right)
arrFlipUD = np.flipud(arr) # flip y (Upside Down)
arrRotate180 = np.fliplr(np.flipud(arr)) # flip x and y -> rotate 180

#==== Rotate =======================
# Rotate CounterClockWise - k=1(default): 90 / k=2: 180 / k=3: 270 / k=-1: -90(=270)
arrRotate90 = np.rot90(arr) # Rotate 90
arrRotate270 = np.rot90(arr, k=-1) # Rotate -90

[ Math and Ufunc ]

ufunc: universal function. ufunc doc
vanilla python처럼 일일이 다 계산하지 않고, ndarray로 vectorization해서 element-wise(훨씬 효율적으로) 계산한다.

Basic Arithmetic Operation

arr = np.array([[1, 2, 3], [4, 5, 6]])

# Convinient Arithmetic Operation
arr2 = arr + 1 # add 1 to entire element of arr
arr2 = arr - 2
arr2 = arr * 3
arr2 = arr / 4 # Automatically Convert arr.dtype to float
arr2 = arr ** 5
# same as above
arr2 = np.add(arr, 1)
arr2 = np.subtract(arr, 2)
arr2 = np.multiply(arr, 3)
arr2 = np.devide(arr, 4)
arr2 = np.exp(arr, 5)

# BraodCasting
arr2 = arr + 1
arr2 = arr + np.array([3, 2, 1]) # add to entire ROWs

# Arithmetix Operation
arr2 = np.sqrt(arr)
arr2 = np.log2(arr)

np.mean
np.std
np.var
np.min
np.max(arr) # max value per every ROW
np.maximun(arr, 3) # if element < 3, then element = 3
np.argmin

#and so on.....

# Arithmetic Operation between elements
addedNum = arr.sum() # sum entire element of arr. 21
addedROW = arr.sum(axis=0) # sum elements in ROW direction. array([5, 7, 9])
addedCOL = arr.sum(axis=1) # sum elements in COL direction. array([ 6, 15])
# same as above
addedROW = np.add.reduce() # default is 'axis=0'
addedCOL = np.add.reduce(axis=1)
clipped = np.clip(arr, 0, 255)

Degree & Radian

대부분의 method는 radian을 사용.

deg = 30
rad = np.deg2rad(deg)

np.cos(rad)
np.sin(rad)

Coordinate System

# Meshgrid: we can get all position of meshgrid points
x = np.arange(0, 3)
y = np.arange(5, 9)

xx, yy = np.meshgrid(x, y)
# xx            yy
[[0 1 2]      [[5 5 5]
 [0 1 2]       [6 6 6]
 [0 1 2]       [7 7 7]
 [0 1 2]]      [8 8 8]]

all_positions_in_meshgrid = np.c_[xx.ravel(), yy.ravel()]
# [[0, 5], [1, 5], [2, 5], [0, 6], [1, 6], ... , [2, 8]]
# made all possible points using x, y

[ Random ]

무작위 int / float 생성

Random Sequence Generator / Random Single Number

#==== Generate Random Suquence =======================
np.random.seed(123) # Seeding can reproduce sequence.
rng1 = np.random.RandomState(seed=123) # Same as above
rng1.rand(3)
rng2 = np.random.default_rng(seed=123) # Same as above
rnd2.rand(3)

#==== Single random Number with Range =======================
np.random.random() # returns [0, 1) float
np.random.randint(0, 10) # returns [0, 10) int
np.random.choice([3, 4, 5]) # returns random element in given list

Random value ndarray (Uniform/Normal)

#==== ndarray with uniform distribution =======================
# [0,1) range 
arr = np.random.rand(2, 3) # generate 2 dim, 2x3 matrix with random numbers
# custom range
np.random.uniform(low=-1, high=1, size=5) # Returns random float in Uniform Distribution between [low,high) (<np.ndarray>, 1 dim, 5)

#==== random ndarray with Distribution =======================
# avg=0, std=1
arr = np.random.randn(2, 3) # generate 2 dim, 2x3 matrix with random numbers of standard
# custom avg, std
np.random.normal(loc=1, scale=1, size=(2, 3)) # Returns random float in Normal Distribution from loc, stancdard deviation is scale. (<np.ndarray>, 2 dim, 2X3)

Shuffle / Permutation

shuffle: in-place method 원본 변경
permutation: out-of-place method 원본 유지

np.random.shuffle([0, 1, 2, 3])
np.random.permutation([0, 1, 2, 3]) # returns shuffled given list
np.random.permutation(5) # returns shuffled list [0, 1, 2, 3, 4]

[ Linear Algebra ]

선형대수 계산.
matrix: <np.ndarray>

Basic Vector / Transpose

row_vector = np.array([1, 2, 3]) # 1X31

#==== Transpose =======================
arr = np.arange(24).reshape(2, 3, 4) # 3 dim, 2X3X4
arr2 = arr.T # 3 dim, 4X3X2
arr3 = arr.transpose(2, 1, 0) # same as above. 
arr3 = arr.transpose(1, 2, 0) # 3 dim, 3X4X2

Dot Product / Cross Product / Element-wise Multip...

A = np.arange(6).reshape(3, 2)
B = np.arange(6).reshape(2, 3)
#==== · Dot Product =======================
arr = np.dot(np.array([1, 2, 3]), np.array(2, 3, 4)) # Vector rotates automatically
arr = np.dot(A, B) # (3X2)X(2X3) = (3X3)
arr = A @ B # same as above
arr = np.matmul(A, B) # same as above

#==== × Cross Product =======================
T = np.array([a, b, c])
v = np.array([1, 2, 3])
arr = np.cross(T, v)
# cross Product: T × v = T_ @ v   # same as above
T_ = [[0, -c, b],
	[c, 0, -a],
	[-b, a, 0]]
result = T_ @ v

#==== ⊙ Element-wise Multiplication =======================
arr = np.multiply(A, A)
arr = A * A # same as above

linalg

Norm / Inverse / Determinant / Eigen / SVD
# dot(), cross() method is in basic np class.

np.linalg.norm(arr) # returns Euclidean Norm 크기

np.linalg.inv(matrix) # returns inverse matrix 역행렬
np.linalg.det(matrix) # returns determinant of matrix 행렬식
np.linalg.eig(matrix) # returns TUPLE (eigen values, eigen vectors) (고유값, 고유벡터)
np.linalg.svd(matrix) # returns TUPLE (U, S, V) of Singular Value Decomposition 특이값 분해

Fourier Transform

spacial domain -> frequency domain
magnitude spectrum: 파형의 크기; 각 주파수 성분이 얼마나 강한지; 이미지의 구조, 밝기, 패턴
phase spectrum: 파형의 위상; 각 주파수 성분이 어디에 위치해 있는지; 이미지에서 패턴의 위치, 방향성

arr = np.arange(16).reshape((4, 4))

# FFT
f = np.fft.fft2(arr) # 2-dim Fast Fourier Transform. 
# spacial domain -> frequency domain # center: 고주파, edge: 저주파
fshift = np.fft.fftshift(f) # Relocate center and edge 
# center: 저주파, edge: 고주파

magnitude_spectrum = 20 * np.log(np.abs(fshift)) # magnitude: l-2 norm
phase_spectrum = np.angle(fshift) # phase: arc tan(a/b)

# process
magnitude_modified = magnitude_spectrum

# iFFT
frequencies = np.exp(magnitude_modified / 20))
fshift_modified = np.abs(frequencies) * np.exp(1j * phase_spectrum)
fshift_modified = fshit_modified.astype(np.unit8) # complex128 -> uint8
reconstructed_image = np.fft.ifft2(np.fft.ifftshift(fshift_modified))

'Programming Language > Python' 카테고리의 다른 글

Sklearn  (0) 2026.01.26
Seaborn  (0) 2026.01.20
Matplotlib  (0) 2026.01.20
Pandas  (0) 2026.01.20