본문 바로가기
Python/Build setting

[Numpy]넘파이 배열 생성(dtype, astype)

by 소소한 혜밍씨 2022. 8. 24.

자료 구조를 보다보면 데이터타입을 계속 확인하는 것이 기본이 된다.

 

가끔 데이터 전처리를 하다보면 에러가 생기는데 많은 확률로 dtype이 맞지 않아서 그런 경우가 있기 때문!

 

numpy array의 dtype은 따로 지정하지 않을 경우 default 로 int형(문자)으로 지정이 된다.

 

 

# 기본형, 지정형(float, int)
a = np.array([1, 2, 3])
b = np.array([1, 2, 3], dtype=np.float64)
c = np.array([1, 2, 3], dtype=np.int32)



# 출력(dtype)
int64 float64 int32

 

 

 

 

그러나 지정하고 싶은 경우 혹은 dtype을 변경하고 싶은 경우에는 아래의 코드를 참고하자.

 

# float 형
i = np.array([1, 2, 3], dtype=np.float64)


# float 형을 int형으로 변환
i = i.astype(np.int32)


# 기존 데이터의 dtype에 맞추어서 변환
j = np.array([1, 2, 3], dtype=np.float64)

j = j.astype(i.dtype)

 

댓글