numpy - 자료형, 연산

KDG·2021년 2월 5일
1

1. numpy 자료형

numpy의 ndarray는 하나의 ndarray 객체 당 하나의 자료형만 지정 가능

2. ndarray 자료형 할당

# 자료형을 명시하지 않으면 float64로 default 할당
# 1.0과 같은 float형이기 때문
nd1 = np.array([1.0, 2.1, 3.0, 4.2]) 


# 자료형을 명시하지 않으면 int32로 default 할당
# 1과 같은 int형이기 때문
nd2 = np.array([[1, 2, 3], [4, 5, 6]]) 


# ndarray 생성시 float32로 자료형을 지정
# array 안에 숫자를 int형식으로 입력해도 float32로 지정했기 때문에 1.과 같은 float형식으로 출력
nd2 = np.array([[1, 2, 3], [4, 5, 6]], dtype = np.float32)
 -> array([[1., 2., 3.],
           [4., 5., 6.]], dtype=float32)
           
           
# ndarray 생성시 float64로 자료형을 지정
# array 안에 숫자를 int형식으로 입력해도 float32로 지정했기 때문에 1.과 같은 float형식으로 출력           
nd2 = np.array([[1, 2, 3], [4, 5, 6]], dtype = ‘float64’)
 -> array([[1., 2., 3.],
           [4., 5., 6.]])
           
           
# ndarray 자료형 확인
print(nd2.dtype)
 -> dtype('float64')
 
 
# ndarray 자료형 형변환
nd2 = nd2.astype(np.int32)
print(nd2.dtype)
 -> dtype('int32')

3. numpy 연산

ndarray는 벡터화 연산(vectorized operation)을 지원하여 별도의 반복문(for loop)을 사용하지 않고
element-wise(같은 위치의 값 끼리)한 반복 연산 가능

0개의 댓글