[라이브러리] 넘파이(Numpy) - ndarray, 메소드, 슬라이싱, 정수 인덱싱

넘파이(Numpy)

- 수치 데이터를 다루는 파이썬 패키지

- 벡터 및 행렬을 사용하는 선형 대수 계산에서 주로 사용

- Numpy는 np라는 명칭으로 import 하는 것이 관례

import numpy as np

 

 

 

np.array()

- 리스트, 튜플, 배열로 부터 ndarray를 생성

-  축의 개수(ndim)와 크기(shape) 존재

import numpy as np

vec = np.array([1, 2, 3, 4, 5])
print(vec)
print("vec의 타입 :", type(vec))
[1 2 3 4 5]
vec의 타입 : <class 'numpy.ndarray'>

 

- 2차원 배열을 만들 때는 array() 안에 하나의 리스트만 들어가므로 리스트의 리스트를 넣어야 함

mat = np.array([[10, 20, 30], [40, 50, 60]])
print(mat)
print("mat의 타입 :", type(mat))
[[10 20 30]
 [40 50 60]]
mat의 타입 : <class 'numpy.ndarray'>

 

- 축의 개수(ndim)과 크기(shape) 확인

print("vec의 축의 개수 :", vec.ndim)
print("vec의 크기(shape) :", vec.shape)
print("mat의 축의 개수 :", mat.ndim)
print("mat의 크기(shape) :", mat.shape)
vec의 축의 개수 : 1
vec의 크기(shape) : (5,)
mat의 축의 개수 : 2
mat의 크기(shape) : (2, 3)

 

 

 

ndarray 메소드

  • np.zeros()

: 배열의 모든 원소에 0 삽입

zero_mat = np.zeros((2, 3))
print(zero_mat)
[[0. 0. 0.]
 [0. 0. 0.]]

 

  • np.ones()

: 배열의 모든 원소에 1 삽입

one_mat = np.ones((2, 3))
print(one_mat)
[[1. 1. 1.]
 [1. 1. 1.]]

 

  • np.full()

: 배열에 사용자가 지정한 값 삽입

same_value_mat = np.full((2, 3), 2)
print(same_value_mat)
[[2 2 2]
 [2 2 2]]

 

  • np.eye()

: 대각선으로 1이고 나머지는 0인 2차원 배열 생성

eye_mat = np.eye(3)
print(eye_mat)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

 

  • np.random.random()

: 임의의 값을 가지는 배열 생성

rand_mat = np.random.random((2, 3))
print(rand_mat)
[[0.4663687  0.66242496 0.58513136]
 [0.23330898 0.47120081 0.75223669]]

 

  • np.arange()

: 괄호 안에 숫자 n 삽입 시 0부터 n-1까지의 값을 가지는 배열 생성

: 괄호 안에 숫자 3개 i, j, k 삽입 시 i부터 j-1까지 k씩 증가하는 배열 생성

arange_vec = np.arange(10)
print(arange_vec)

arange_n_step_vec = np.arange(0, 10, 2)
print(arange_n_step_vec)
[0 1 2 3 4 5 6 7 8 9]
[0 2 4 6 8]

 

  • np.reshape()

: 기존 데이터를 변경하지 않으면서 배열의 구조 변경

# 0부터 24까지의 숫자를 생성하고 5행 5열의 행렬로 변경
reshape_mat = np.array(np.arange(25).reshape((5,5)))
print(reshape_mat)
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

 

 

 

슬라이싱

- 특정 행이나 열들의 원소들에 접근

mat = np.array([[1,2,3], [4,5,6]])

# 첫번째 행 출력
slicing_mat = mat[0,:]
print(slicing_mat)

# 두번째 열 출력
slicing_mat = mat[:,1]
print(slicing_mat)
[1 2 3]
[2 5]

 

 

 

정수 인덱싱(Integer indexing)

- 원하는 위치의 원소들을 뽑아서 배열 구성

mat = np.array([[1,2],[3,4],[5,6]])

# 1행 0열의 원소 가져옴
print(mat[1,0])

# 2행 1열, 1행 1열의 두 개의 원소를 가지고 배열 생성
indexing_mat = mat[[2,1],[1,1]]
print(indexing_mat)
3
[6 4]

 

 

 

연산

- 사칙연산

x = np.array([1,2,3])
y = np.array([4,5,6])

result = np.add(x,y) # x + y
print(result)

result = np.subtract(x,y) # x - y
print(result)

result = np.multiply(result,x) # result * x
print(result)

result = np.divide(result,x) # result / x
print(result)
[5 7 9]
[-3 -3 -3]
[-3 -6 -9]
[-3. -3. -3.]

 

  • np.dot()

: 행렬곱 계산 

mat1 = np.array([[1,2],[3,4]])
mat2 = np.array([[5,6],[7,8]])
mat3 = np.dot(mat1, mat2)
print(mat3)
[[19 22]
 [43 50]]