Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

주어진 numpy 배열의 데이터 유형 변경

<시간/>

Numpy 배열은 파이썬의 기본 데이터 유형 외에도 매우 다양한 데이터 유형을 지원합니다. 배열이 생성된 후에도 필요에 따라 배열에 있는 요소의 데이터 유형을 수정할 수 있습니다. 이 목적에 사용되는 두 가지 방법은 array.dtype입니다. 및 array.astype

array.dtype

이 방법은 배열에 있는 요소의 기존 데이터 유형을 제공합니다. 아래 예에서는 배열을 선언하고 해당 데이터 유형을 찾습니다.

import numpy as np# Create a numpy arraya =np.array([21.23, 13.1, 52.1, 8, 255])# Print the arrayprint(a)# 배열 인쇄 dat typeprint(a.dtype)

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

[ 21.23 13.1 52.1 8. 255. ]float64

배열.astype

이 방법은 기존 배열을 원하는 데이터 유형의 새 배열로 변환합니다. 아래 예에서는 주어진 배열을 다양한 대상 데이터 유형으로 변환합니다.

import numpy as np# Create a numpy arraya =np.array([21.23, 13.1, 52.1, 8, 255])# Print the arrayprint(a)# 배열 인쇄 dat typeprint(a.dtype)# 변환 배열 데이터 유형을 int32a_int =a.astype('int32')print(a_int)print(a_int.dtype)# 배열 데이터 유형을 stra_str로 변환 =a.astype('str')print(a_str)print(a_str.dtype )# 배열 데이터 유형을 complexa_cmplx =a.astype('complex64')print(a_cmplx)print(a_cmplx.dtype)로 변환

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

<이전>[ 21.23 13.1 52.1 8. 255. ]float64[ 21 13 52 8 255]int32['21.23' '13.1' '52.1' '8.0' .255.0']<.213[ j 52.1 +0.j 8. +0.j 255. +0.j]complex64