Return True if cast between data types can occur controlling what kind of data casting may occur in Python


The numpy.can_cast() method returns True if cast between data types can occur according to the casting rule. The 1st parameter is the data type or array to cast from. The 2nd parameter is the data type to cast to. The 3rd parameter controls what kind of data casting may occur, with values ‘no’, ‘equiv’, ‘safe’, ‘same_kind’ and ‘unsafe’,

  • ‘no’ means the data types should not be cast at all.

  • ‘equiv’ means only byte-order changes are allowed.

  • ‘safe’ means only casts which can preserve values are allowed.

  • ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.

  • ‘unsafe’ means any data conversions may be done.

Steps

At first, import the required library −

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'))

Example

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'))

Output

Checking with can_cast() method in Numpy

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

Updated on: 25-Feb-2022

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements