Numpy의 기본
- Numerical Python의 줄임말인 Numpy는 고성능의 과학계산 컴퓨팅과 데이터 분석에 필요한 기본 패키지이다.
- 수치 데이터에 사용하는 빠르고 효율적인 다차원 데이터 컨테이너인
ndarray
를 제공한다. (python의 list보다 빠르다!)
ndarray
numpy.array([])
: ()괄호 안에 [] 괄호를 넣어야 한다.
- 즉, array는 list로 만든다.
- print를 하면 콤마 없이 [] 괄호 안에 띄어쓰기로 구분되어 출력한다.
import numpy as np
a = np.array([1, 2, 3])
- 1차 뿐만 아니라 n차 array에 대한 출력 결과도 콤마로 구분하지 않는다.
- 2차 array의 경우 ([]) 안에 ()로 묶인 튜플이 콤마로 구분되어 들어감
- 결과는 [] 괄호 안에 [] 괄호가 들어간 형태
b = np.array([(1, 2, 3), (4, 5, 6)])
b = np.array([[1, 2, 3], [4, 5, 6]])
print(b)
[[1 2 3]
[4 5 6]]
numpy 배열 생성하기
- np.arange(n) : 0부터 n-1까지 n개의 숫자가 있는 array 반환
- np.arange(start, end, interval) : 시작부터 간격만큼 더해서 끝보다 작은 수 출력
a = np.arange(10)
print(a)
print(a.shape)
b = np.arange(0, 10, 2)
print(b)
print(b.shape)
- np.zeros(n) : n개의 0 출력 결과가 0. 으로 나온다.
- np.zeros((n, m)) : n개의 0. 출력 (m이 있을 경우 n X m 행렬 출력)
c = np.zeros(5)
print(c)
d = np.zeros((3, 2))
print(d)
[[0. 0.]
[0. 0.]
[0. 0.]]
print(d.shape)
(3, 2)
- np.full((n, m), x) : x로 가득찬 n X m 행렬의 ndarray
a = np.full((2, 3, 4), 8))
print(a)
[[[8 8 8 8]
[8 8 8 8]
[8 8 8 8]]
[[8 8 8 8]
[8 8 8 8]
[8 8 8 8]]]
- np.eye(n) : nxn ndarray에 대각선만 1. 나머지는 0.으로 채운다.
a = np.eye(4)
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
- np.random.random((n, m)) : 0이상 1미만의 값으로 채워진 n x m 행렬 ndarray (괄호가 두 개 들어간다.)
a = np.random.random((3, 2))
[[0.06962667 0.87704521]
[0.32205301 0.1144304 ]
[0.32638222 0.25040487]]
Array indexing
- 파이썬 list 자료형을 np.array(list)를 통해 ndarray로 변환할 수 있다.
temp_list = [1, 2, 3]
temp_ndarray = np.array(temp_list)
print(temp_ndarray)
[1 2 3]
- 파이썬 list 2개 이상으로 2차원 array를 만들 때는 np.array([list1, list2, ...]) 형태이다.
temp_list2 = [4, 5, 6]
temp = np.array([temp_list, temp_list2])
print(temp)
[[1 2 3]
[4 5 6]]
만약 행과 열의 길이가 다르면
[list([1, 2, 3]) list([4, 5, 6, 7])]
이런 식으로 출력된다.
print(temp_ndarray[0])
print(temp[0:3])
print(temp[1])
print(temp[:, 1])
print(temp[0:2, 1:3])
[[2 3]
[5 6]]
Boolean indexing
- array를 조건식에 대입하면 각 값에 대해 True, False를 반환한다.
print(temp_ndarray>2)
print(temp_ndarray > temp[0, 2])
- 조건식을 괄호 안에 넣어서 조건에 맞는 값만 출력이 가능함!
print(temp_ndarray[temp_ndarray>1])
nums = np.arange(20)
odd_nums = nums[nums%2 == 1]
print(odd_nums)
a=np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]])
b = a[-2:, -3:]
print(b)
[[ 8 9 10]
[13 14 15]]
- b 값을 수정하면 원래 array인 a의 값들이 변경됨에 유의하자
b[1, 2] = 77
print(b)
[[ 8 9 10]
[13 14 77]]