14. Numpy Arrays
드디어 넘파이!!!!!!!
import numpy as np
넘파이에 들어있는 함수들을 사용하기 위해 numpy를 np라는 간단한 형태로 불러와 준다.
list 와 numpy array
nums_list = list(range(5))
nums_np = np.array(range(5))
[0, 1, 2, 3, 4]
array([0, 1, 2, 3, 4])
int가 들어가 있는 numpy array 는 dtype('int64') nums_np_ints.dtype
float가 들어가 있는 numpy array는 dtype('float64') nums_np_floats.dtype
array의 타입이 어떻게 나오는지 궁금해서
print(type(nums_np)) 하면
<class 'numpy.ndarray'>가 출력됨
Broadcasting
: 크기가 다른 배열 간의 연산
*파이썬의 리스트는 불가능하지만 numpy array는 가능하다.
numpy를 쓰는 이유랄까?
nums = [-2, -1, 0, 1, 2] # 리스트
nums ** 2 # TypeError 발생
sqrd_nums = []
for num in nums:
sqrd_nums.append(num ** 2) # inefficient option
print(sqrd_nums) # [4, 1, 0, 1, 4]
sqrd_nums = [num ** 2 for num in nums] # better but not the best
print(sqrd_nums)
nums_np = np.array([-2, -1, 0, 1, 2]) # 넘파이 어레이
nums_np ** 2 # array([4, 1, 0, 1, 4])
a = nums_np # [4, 1, 0, 1, 4]
인덱싱도 동일하게 할 수 있는데 numpy array같은 경우는 array(리스트) 이런식으로 출력됨
nums = [-2, -1, 0, 1, 2]
nums_np = np.array(nums)
nums[2] # 0
nums_np[2] # 0
nums[-1] # 2
nums_np[-1] # 2
nums[1:4] #[-1, 0, 1]
nums_np[1:4] # array([-1, 0, 1])
# 2차원 리스트
nums = [[1,2,3],[4,5,6]]
nums[0][1] # 2 # 2차원 인덱싱
[row[0] for row in nums] # [1,4]
# 2차원 array
nums_np = np.array(nums) # 만든 리스트를 넣어주기
nums_np[0,1] # 2
nums_np[:,0] # array([1,4])
numpy array 는 ,를 사이에 두고 두개의 값을 인덱스로 받는데
, 앞에 있는 값은 행의 index
, 뒤에 있는 값은 열의 index
저 위에 nums_np[:,0]에 있는 인덱스를 자세히 들여다보면
행의 인덱스에 아무것도 없이 : 를 두었음 - range에서 설명했던 개념에 따라 처음부터 끝까지를 잡고 있음
열의 인덱스에 0을 두었음 - 열에서 0에 해당하는 애들만 뽑겠다는 뜻
Boolean Indexing
numpy array에서 원하는 값만 뽑아내기
nums = [-2, -1, 0, 1, 2]
nums_np = np.array(nums)
nums_np > 0 # array([False, False, False, True, True])
nums_np[nums_np > 0] # array([1, 2])
numpyArray이름[기준] 을 통해 기준을 만족하는 값을 뽑아낼 수 있다.
* 만약 이걸 list에서 하려면?
pos = [] # inefficient code
for num in nums:
if num > 0:
pos.append(num)
print(pos) # [1, 2]
pos = [num for num in nums if num > 0] # better but not the best
print(pos) # [1, 2]