슬기로운 개발자생활/Python

[찾기 쉬운 Python 코드] Numpy

개발자 소신 2020. 12. 27. 00:14
반응형

안녕하세요 ! 소신입니다.

 

 

사용법 + 예제 코드까지 이해하고 찾기 쉽게 정리해놓았습니다

 

찾기 : CTRL+F로 검색어를 입력해보세요

 


 

 

#np.nan #np.inf

np.nan + 1 => np.nan
1 + np.nan => np.nan

np.inf + 1 => np.inf
1 + np.ifn => np.inf

 

#vstack #hstack

#numpy 배열 합치기, 가로 합치기, 세로 합치기, 열 합치기, 행 합치기

# vstack
a = np.ones((1,5)) # 1x5
b = np.ones((1,3)) # 1x3

d = np.c_[a,b] # 1x8
d, d.shape
# OUT >>> array([[1., 1., 1., 1., 1., 1., 1., 1.]]), (1, 8)

# hstack
a = np.ones(5) # 5x1
b = np.ones(1) # 1x1

c = np.r_[a,b] # 6x1
c, c.shape
# OUT >>> array([1., 1., 1., 1., 1., 1.]), (6,)

 

# np.concatenate # numpy 합치기 # concat numpy

# row span
a = np.array([5,3,4,5,2]) # 5 x 1
b = np.array([2,8,1,9,7]) # 5 x 1
c = np.concatenate((a, b), axis=0) # 10 x 1 
c
# OUT >>> array([5, 3, 4, 5, 2, 2, 8, 1, 9, 7])

# c = np.concatenate((a,b), axis=1)
# error

# column span
a = np.array([5,3,4,5,2]).reshape(-1, 5) # 1 x 5
b = np.array([2,8,1,9,7]).reshape(-1, 5) # 1 x 5
c = np.concatenate((a, b), axis=0)
c.shape # 2 x 5

c = np.concatenate((a, b), axis=1)
c.shape # 1 x 10

 

# Indexing, 인덱싱, slice, slicing

# 행 순서 바꾸기 # 열 순서 바꾸기

# row change #column change

boxes = np.eye(8) # 8x8
boxes = [:,[0,4,1,5]] # 모든 행, 0, 4, 1, 5번째 열
# OUT >>>
# array([[1., 0., 0., 0.], 0번째 열 (0열)
#        [0., 0., 1., 0.], 1번째 열 (2열)
#        [0., 0., 0., 0.],
#        [0., 0., 0., 0.],
#        [0., 1., 0., 0.], 4번째 열 (1열)
#        [0., 0., 0., 1.], 5번째 열 (3열)
#        [0., 0., 0., 0.],
#        [0., 0., 0., 0.]])

 

# numpy to list

# 리스트로 바꾸기

boxes = np.zeros(5)
boxes_list = boxes.tolist() # float

# Never use np.tolist(boxes)
# error

 

# type # dtype # 형변환 # change type

np.array(a, dtype=np.uint8) # for image
np.array(a, dtype=np.int64) # =long 8, 16, 32
np.array(a, dtype=np.float64) # float, 32

a = np.array([5,3,4,5,2], dtype=np.float64)
print(a)
# OUT >>> [5. 3. 4. 5. 2.]
a.astype(np.uint8)
# OUT >>> array([5, 3, 4, 5, 2], dtype=uint8)

 

# reshape

a = np.array([5,3,4,5,2]).reshape(-1, 5) # 1 x 5

# .reshape(a, b, c, d) a*b*c*d = number of np.array elements

 

# list to numpy array # list ndarray # 리스트 넘파이 배열 변환 # np array

# tuple to numpy array # tuple ndarray # 튜플 넘파이 배열 변환

# list to numpy array
a = [[5,3,4,5,2], [5,3,4,5,2]]
b = np.asarray(a)
b.shape
# OUT >>> (2,5)

# tuple to numpy array
a = ((5,3,4,5,2), (5,3,4,5,2))
b = np.asarray(a)
b.shape

 

# numpy delete row # numpy delete column

# numpy 행 삭제 # numpy 열 삭제

np.delete(arr, index, axis) # 0 = row, 1 = col

a = np.zeros((5,3))
print(a.shape) # OUT >>> (5, 3)

# DELETE ROW
b = np.delete(a, 0, 0)
print(b.shape) # OUT >>> (4, 3)

# DELETE COLUMN
c = np.delete(a, 1, 1)
print(c.shape) # OUT >>> (5, 2)

# OR JUST USE SLICING
d = a[[1,2,3,4], :]
print(d.shape) # OUT >>> (4, 3)

e = a[:, [1,2]]
print(e.shape) # OUT >>> (5, 2)

# f = a[[1,2,3], [2,1]]
# ERROR

 

반응형