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

데이터 유형 간의 캐스트가 발생할 수 있으면 Python에서 발생할 수 있는 데이터 캐스트의 종류를 제어하는 ​​경우 True를 반환합니다.

<시간/>

numpy.can_cast() 메서드는 캐스팅 규칙에 따라 데이터 형식 간의 캐스팅이 발생할 수 있는 경우 True를 반환합니다. 첫 번째 매개변수는 캐스트할 데이터 유형 또는 배열입니다. 두 번째 매개변수는 캐스트할 데이터 유형입니다. 세 번째 매개변수는 'no', 'equiv', 'safe', 'same_kind' 및 'unsafe' 값을 사용하여 발생할 수 있는 데이터 캐스팅 유형을 제어합니다.

  • 'no'는 데이터 유형이 전혀 캐스트되지 않아야 함을 의미합니다.

  • 'equiv'는 바이트 순서 변경만 허용됨을 의미합니다.

  • 'safe'는 값을 보존할 수 있는 캐스트만 허용됨을 의미합니다.

  • 'same_kind'는 안전한 캐스트 또는 float64에서 float32와 같은 종류 내 캐스트만 허용됨을 의미합니다.

  • '안전하지 않음'은 모든 데이터 변환이 완료될 수 있음을 의미합니다.

단계

먼저 필요한 라이브러리를 가져옵니다 -

import numpy as np

numpy.can_cast() 메소드는 캐스팅 규칙에 따라 데이터 유형 간의 캐스트가 발생할 수 있는 경우 True를 반환합니다. -

print("Checking with can_cast() method in Numpy\n")

유형 "아니오" -

print("Result...",np.can_cast('i8', 'i8', 'no'))
print("Result...",np.can_cast('<i8', '>i8', 'no'))

"equiv" 유형 -

print("Result...",np.can_cast('<i8', '>i8', 'equiv'))
print("Result...",np.can_cast('<i4', '>i8', 'equiv'))

"안전한" 유형 -

print("Result...",np.can_cast('i4', 'i8', 'safe'))
print("Result...",np.can_cast('i8', 'i4', 'safe'))

"same_kind" 유형 -

print("Result...",np.can_cast('i8', 'i4', 'same_kind'))
print("Result...",np.can_cast('i8', 'i4', 'same_kind'))

예시

import numpy as np

# The numpy.can_cast() method returns True if cast between data types can occur according to the casting rule.

print("Checking with can_cast() method in Numpy\n")

# The type "no"
print("Result...",np.can_cast('i8', 'i8', 'no'))
print("Result...",np.can_cast('<i8', '>i8', 'no'))

# The type "equiv"
print("Result...",np.can_cast('<i8', '>i8', 'equiv'))
print("Result...",np.can_cast('<i4', '>i8', 'equiv'))

# The type "safe"
print("Result...",np.can_cast('i4', 'i8', 'safe'))
print("Result...",np.can_cast('i8', 'i4', 'safe'))

# The type "same_kind"
print("Result...",np.can_cast('i8', 'i4', 'same_kind'))
print("Result...",np.can_cast('i8', 'i4', 'same_kind'))

출력

Checking with can_cast() method in Numpy

Result... True
Result... False
Result... True
Result... False
Result... True
Result... False
Result... True
Result... True