2 분 소요

1. Numpy(Numerical Python)란?

  • 파이썬에서 선형대수 기반의 프로그램을 만들 수 있도록 지원하는 라이브러리

2. 배열 생성법

1) 라이브러리 코드

import numpy as np


2) 배열 생성

2-1) 리스트 활용

  • 1차원
dim1_list = [1,2,3]
a1 = np.array(dim1_list)
$$ a_1 = \begin{pmatrix} 1 \\ 2 \\ 3 \end{pmatrix} $$
  • 2차원 예시 : $((1, 2, 3), (4,5,6))$
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)
$$ a_{21}= \begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{pmatrix} \qquad a_{22}= \begin{pmatrix} \begin{pmatrix} 1 \\ 2 \\ 3 \end{pmatrix} \end{pmatrix} $$


2-2) 생성 함수 : arange, zeros, ones, zeros_like, ones_like, full, random.rand, random.random, eye

  • ☑️ arange
arr = np.arange(5)
arr2 = np.arange(1, 16, 3)  # 마지막 숫자인 16은 미포함
$$ arr = \begin{pmatrix} 0 \\ 1 \\ 2 \\ 3 \\ 4 \end{pmatrix} \qquad arr_2 = \begin{pmatrix} 1 \\ 4 \\ 7 \\ 10 \\ 13 \end{pmatrix} $$


  • ☑️ zeros
zer = np.zeros(2,3)
$$ zer= \begin{pmatrix} 0 & 0 & 0 \\ 0 & 0 & 0 \end{pmatrix} $$


  • ☑️ ones
one = np.ones(3,2)
$$ one = \begin{pmatrix} 1 & 1 \\ 1 & 1 \\ 1 & 1 \end{pmatrix} $$


  • ☑️ zeros_like
sample = [[1, 2, 3], [4, 5, 6]]
zer_l = np.zeros_like(sample) # 변수로 리스트, 배열 모두 가능
$$ zer-L = \begin{pmatrix} 0 & 0 & 0 \\ 0 & 0 & 0 \end{pmatrix} $$


  • ☑️ ones_lie
sample = [[1, 2, 3], [4, 5, 6]]
one_l = np.ones_like(sample) # 변수로 리스트, 배열 모두 가능
$$ one-L = \begin{pmatrix} 1 & 1 & 1 \\ 1 & 1 & 1 \end{pmatrix} $$


  • ☑️ full
ful = np.full((2,3),5)
$$ ful = \begin{pmatrix} 5 & 5 & 5 \\ 5 & 5 & 5 \end{pmatrix} $$


  • ☑️ random.rand / ☑️ random.random
ran1 = np.random.rand(2,2)
ran2 = np.random.random((2,2))
$$ ran_1, \; ran_2 = \begin{pmatrix} 0.xxx & 0.xxx \\ 0.xxx & 0.xxx \end{pmatrix} $$


  • ☑️ eye
eye = np.eye(3)
$$ eye = \begin{pmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{pmatrix} $$


2-3) 변형 함수 : reshape, flatten

  • ☑️ reshap
sample_array = np.arange(6)
res = sample_array.reshape(2,3)
res_F = sample_array.reshape(2,3, order='F')

✨ reshape(x1, x2) 에서 x1, x2 중 하나만 -1을 넣어도 행열에 맞추어 변형시켜줌!

$$ sample-array = \begin{pmatrix} 0 \\ 1 \\ 2 \\ 3 \\ 4 \\ 5 \end{pmatrix} \; \rightarrow \; res = \begin{pmatrix} 0 & 1 & 2 \\ 3 & 4 & 5 \end{pmatrix} $$ $$ sample-array = \begin{pmatrix} 0 \\ 1 \\ 2 \\ 3 \\ 4 \\ 5 \end{pmatrix} \; \rightarrow \; res-F = \begin{pmatrix} 0 & 2 & 4 \\ 1 & 3 & 5 \end{pmatrix} $$


  • ☑️ 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]
$$ sample-array = \begin{pmatrix} 1 \\ 2 \\ 3 \\ 4 \\ 5 \\ 6 \end{pmatrix} \rightarrow \begin{pmatrix} 1 & 3 & 5 \\ 2 & 4 & 6 \end{pmatrix} \rightarrow \begin{pmatrix} 1 \\ 3 \\ 5 \\ 2 \\ 4 \\ 6 \end{pmatrix} $$

댓글남기기