2 분 소요

Numpy

다양한 matrix 계산

고성능 과학 계산용 패키지

일반 list 에 비해 빠르고 메모리 효율적

import numpy as np

*numpy는 하나의 data type만 배열에 넣을 수 있음

(list와 달리 dynamic typing 적용되지 않음)

#string 넣어도 float로 변환됨
test_array = np.array([1,4,5.,"9"], float)

numpy는 array는 파이썬에서 따로따로 주소에 넣는 거와 달리

차례로 값이 들어가기 때문에 연산이 좋아진다.

numpy array 특징 보기

#array 전체의 데이터 type (보통 float32, float64 사용)
numarray.dtype
#array 크기, 형태
numarray.shape
#array 메모리 크기
numarray.nbytes

(3,4,5) 형태이면

3층에 4 row 5 column 인 형태이다

Handling shape

reshape

array의 shape크기를 변경, element 개수는 동일

np.array(test_matrix).reshape(2,4)

#-1 : 알아서 해주세요
np.array(test_matrix).reshape(-1,4)

flatten

다차원 array를 1차원 array로 변환

np.array(test_matrix).flatten()

indexing , slicing

  • Indexing

list와 달리 이차원 배열에서 [~,~] 표기법을 제공합

# 원래
test_example[0][2]
# 이것도 가능
test_example[0,2]
  • Slicing

list와 달리 행과 열 부분을 나눠서 slicing 가능

-> 부분집합 추출할 때 유용

a = np.array([[1,2,3,4,5],[6,7,8,9,10]], int)

a[:,2:]		#전체 row의 2열 이상
a[1,1:3]	#1 row 의 1열~ 2열
a[1:3]		#1 row ~ 2row 전체
a[:,::2]  #전체 row의 처음부터 두 칸씩 뛰어 넘은 값

creation function

  • arange

python의 range 느낌

list와 다른 점은 step 정할때 float 형태도 가능함

np.arange(0,5,0.5)
  • ones, zeros, empty
  • ones_lie, zeros_like, empty_like
  • identity (단위 행렬(i 행렬) 생성)
  • eye (대각선이 1인 행렬, k 값의 시작 index 변경 가능)
  • diag (대각 행렬의 값을 추출)

  • random sampling
np.random.uniform(0,1,10) #균등분포
np.random.normal(0,1,10) #정규분포
np.random.exponential(scale= 2, size=100)

operation functions

  • sum, mean, std, ….

axis

operation 할 때 기준이 되는 dimension 축

3d 에서

axis = 0 : 층

axis = 1 : row

axis = 2 : column

  • concatenate

numpy array를 합치는 함수

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

b = b[np.newaxis,:]
np.concatenate((a,b.T),axis = 1)

array operations

numpy는 기본적인 사칙연산 가능

shape가 같으면 ‘element-wise operations’ 일어난다

  • dot product

dot 함수 이용

test_a.dot(test_b)
  • transpose

transpose 또는 T 이용

test.transpose()
test.T
*** broadcasting 지원 됨

shape 다른 배열간 연산 지원

-> matrix 와 scalar 간 연산 가능

-> matrix 와 vector 간 연산 가능

comparison

  • all & any

all : 데이터 전부가 조건에 만족(and)

any : 데이터 일부가 조건에 만족(or)

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

np.all(a<10)
np.any(a>4)

boolean값 나옴(true false)

  • element-wise 비교 (with. ==, > , < , …)

배열의 크기가 동일할 때 각각 원소끼리 비교됨

  • logical_

​ 조건을 줌

np.logical_and(a>0,a<3)
np.logical_not(b)
np.logical_or(b,c)
  • np.where
#true, false값 지정
np.where(condition, True, False)
#true index값 반환
np.where(condition)
# nan : not a number
np.isnan(a)
# NaN 값 입력
np.NaN

# is finite number
np.isfinite(a)
# finite 값 입력
np.Inf
  • argmax & argmin

array 내 최대,최소값 index 반환

np.argmax(a, axis = 1)
  • argsort

sort 한 index 반환

boolean, fancy index

  • boolean index

특정 조건에 따른 값을 배열 형태로 추출

  • fancy index

numpy는 array를 index value로 사용해서 값 추출

a = np.array([2,4,6,8],float)
b = np.array([0,0,1,3,2],int)
a[b]


a.take(b)

loadtxt, savetxt

# txt 파일 추출
a = np.loadtxt('./population.txt' ,delimeter = "\t")

a_int = a.astype(int)

# csv 저장
np.savetxt("int_data_2.csv", a_int, fmt = "%.2", delimeter = ",")
#fmt = format 
# pickle 형태로 저장
np.save("npy_test_object", arr = a_int)

#load
a_test = np.load(file= "npy_test_object.npy")

태그:

카테고리:

업데이트:

댓글남기기