파이썬의 데이터는 실행 중에 데이터 타입이 바뀔 수 있는 인터프리터 언어다. 이로 인한 간단함과 직관성은 파이썬의 장점이지만, 다른 정적 타입 컴파일 언어에 비해 속도가 느리다는 단점또한 있다.
numpy 라이브러리는 배열 계산에서 이러한 파이썬의 단점을 극복하기 위해 생겨난 라이브러리다. C 언어로 컴파일 되어 있으며, Python에서는 해당 API를 호출하여 C언어의 기능을 활용하는 형식이다.
구체적으로 numpy의 array에 비해 python의 list는 왜 느릴까?
/* C언어의 int형 */
int result = 0;
/* Python의 객체 */
struct _longobject {
long ob_refcnt;
PyTypeObject *ob_type;
size_t ob_size;
long ob_digit[1];
};
그에 반해 numpy의 array는 데이터 하나가 차지하는 공간이 C언어의 원시데이터형 만큼만 데이터를 차지하므로 훨씬 빠르게 처리할 수 있다

numpy 속성
import numpy as np
# 다양한 차원의 배열 생성
x1 = np.random.randint(10, size=6) # 1차원 배열 생성
x2 = np.random.randint(10, size=(3, 4)) # 2차원 배열 생성
x3 = np.random.randint(10, size=(3, 4, 5)) # 3차원 배열 생성
print('x3 차원갯수:', x3.ndim)
print('x3 배열 구조:', x3.shape)
print('x3 크기:', x3.size)
배열 데이터 다루기
# array 자르기 -> x[start:stop:end]
print(x1[0:4:2]) # [9 7]
# 배열 복사하기
x2_sub_copy = x2[:2, :2].copy()
print(x2_sub_copy)
# [[0 5]
# [9 6]]
# 배열 모양 변경하기
grid = np.arange(1, 10).reshape((3, 3))
print(grid)
# [[1 2 3]
# [4 5 6]
# [7 8 9]]
# 차원 추가하기
x = np.array([1, 2, 3])
# 0 axis 추가
print(x.reshape((1, 3))) # [[1 2 3]]
print(x[np.newaxis, :]) # [[1 2 3]]
# 1 axis 추가
print(x.reshape((3, 1)))
print(x[:, np.newaxis])
# [[1]
# [2]
# [3]]
# 배열 합치기
x = np.array([1, 2, 3])
y = np.array([3, 2, 1])
np.concatenate([x, y])
sum
big_array = np.random.rand(1000000)
%timeit sum(big_array)
%timeit np.sum(big_array)
# 72 ms ± 1.17 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 936 µs ± 36.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
min
%timeit min(big_array)
%timeit np.min(big_array)
# 52.1 ms ± 429 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 432 µs ± 53.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Operation Equivalent ufunc Description