본문 바로가기

부스트캠프 AI Tech/Python

Numpy

Numerical Python

  • 일반 list에 비해 빠르고 효율적
    • python의 list는  mem address를 저장하지만, ndarray는 값을 직접 저장
    • list는 값의 변경이 용이하고 ndarray는 속도가 빠름
  • C++, 포트란 등과 통합 가능
  • import numpy as np 국룰
  • 하나의 data type만 넣을 수 있음 (dynamic typing x)
a = [1, 2, 3]
b = [3, 2, 1]
a[0] is b[-1] # True
a = np.array(a)
b = np.array(b)
a[0] is b[-1] # False
  • shape : array의 dimension 반환 (tuple)
    • 1d : (col,), 2d : (row, col), 3d : (channel, row, col)
  • dtype : array의 data type 반환
  • ndim : # of dimensions
  • size : # of data

Shape

  • reshape : array의 shape을 변경
    • -1을 넣으면 자동 
  • flatten : n dim array -> 1d array

Indexing & Slicing

a[2][2] = a[2, 2] # numpy에서만 가능
a = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], int)
a[:, 2:] # 전체 row의 col 2 이상
a[1, 1:3] # row 1의 col 1~2
a[1:3] # row 1~2

a[::2,::3]

Creation

arange, zeros, ones, empty, something_like, identity, eye, diag, random.sampling

arange
zeros, ones
empty, init되지 않아서 garbage값이 들어옴
something_like, parameter의 array와 같은 shape
identity, 단위 행렬
eye, N x M의 단위행렬
diag, 대각 행렬 추출, index k로 시작 위치 조정
random.sampling, 정규분포의 parameter (평균, 편차, size)

Operation

mean, std, vstack, hstack, concatenate, newaxis

axis

axis
mean, std
vstack, hstack
concatenate
newaxis, (2,) -> (1,2), (2,1)

Array Operation

scalar, dot product, transpose, braodcasting

dot, 행렬곱 
transpose, 전치행렬
broadcasting

Performance

  • for loop < list comprehension < numpy 
  • 대용량의 계산이 필요하면 반드시 numpy로
  • 계산이 아닌 할당에서는 빠르지 않음

Comparison

any, all where, argmin, argmax, argsort, isnan, isfinite, isinf, boolean index, fancy index

broadcasting이 일어남
any, all
array 간의 비교
boolean array 간의 and, or, not 연산
where
nan, finite, infinite 판별
argmax, argmin, max,min값의 index 반환
axis가 없을 시, flatten하여 max index 반환
argsort, sort한 index 반환, 헷갈리면 하나씩 대입해 보자
boolean index, # of array = # of condition
fancy index, b는 a의 index 범위 내로 설정
row나 col만 지정 가능

Numpy data i/o

  • loadtxt, savetxt
  • numpy object - npy

'부스트캠프 AI Tech > Python' 카테고리의 다른 글

Pandas  (0) 2022.01.23
Data handling  (0) 2022.01.22
Exception/File/Log handling  (0) 2022.01.21
Module  (0) 2022.01.21
Object Oriented Programming  (0) 2022.01.21