1. Numpy(Numerical Python)를 사용하는 이유
파이썬에서 선형대수 기반의 프로그램을 만들 수 있도록 지원하는 라이브러리
2. 배열 생성법
1) 라이브러리 코드
import numpy as np
2) 배열 생성
2-1) 리스트 활용
- 1차원 예시
dim1_list = [1,2,3]
a1 = np.array(1dim_list)
- 2차원 예시
dim2_list1 = [[1,2,3],[4,5,6]]
a2_1 = np.array(dim2_list1)
dim2_list2 = [[1,2,3]]
a2_2 = np.array(dim2_list2)
2-2) 생성 함수 : arange, zeros, ones, zeros_like, ones_like, full, random.rand, random.random, eye
- arange
arr = np.arange(5)
# arr 모양 : [0, 1, 2, 3, 4]
arr2 = np.arange(1, 16, 3)
# arr2 모양 : [1, 4, 7, 10, 13] ~마지막 숫자인 16은 미포함
- zeros
zer = np.zeros(2,3)
# zer 모양 : [[0, 0, 0]
# [0, 0, 0]]
- ones
one = np.ones(3,2)
# one 모양 : [[1, 1]
# [1, 1]
# [1, 1]]
- zeros_like
sample = [[1, 2, 3], [4, 5, 6]]
zer_l = np.zeros_like(sample) # 변수로 리스트, 배열 모두 가능
# zer_l 모양 : [[0, 0, 0]
# [0, 0, 0]]
- ones_lie
sample = [[1, 2, 3], [4, 5, 6]]
one_l = np.ones_like(sample) # 변수로 리스트, 배열 모두 가능
# one_l 모양 : [[1, 1, 1]
# [1, 1, 1]]
- full
ful = np.full((2,3),5)
# ful 모양 : [[5, 5, 5]
# [5, 5, 5]]
- random.rand / random.random
ran1 = np.random.rand(2,2)
ran2 = np.random.random((2,2))
# ran1, 2 모양 : [[0.xxx, 0.xxx]
# [0.xxx, 0.xxx]]
- eye
eye = np.eye(3)
# eye 모양 : [[1, 0, 0]
# [0, 1, 0]
# [0, 0, 1]]
2-3) 변형 함수 : reshape, flatten
- reshape
sample_array = np.arange(6)
res = sample_array.reshape(2,3)
res_F = sample_array.reshape(2,3, order='F')
# res 모양 : [[0, 1, 2]
# [3, 4, 5]]
# res_F 모양 : [[0, 2, 4]
# [1, 3, 5]]
★ reshape(x1, x2) 에서 x1, x2 중 하나만 -1을 넣어도 행열에 맞추어 변형시켜줌!
- faltten
sample_array = np.arange(1, 7) #[1, 2, 3, 4, 5, 6]
sample_array = sample_array.reshape(2, 3, order='F') #[[1, 3, 5] [2, 4, 6]]
sample_array.flatten() #[1, 3, 5, 2, 4, 6]
'Python > Numpy' 카테고리의 다른 글
Numpy 라이브러리 기초 - 3. 배열의 연산 (0) | 2023.11.05 |
---|---|
Numpy 라이브러리 기초 - 2. 배열 속성 확인 (0) | 2023.11.05 |