What is the numpy.can_cast() function in Python?

Overview

The numpy.can_cast() function in Python is used to check if we can cast between given data types according to the rules of casting. It will return True if the casting is possible and False if otherwise.

Syntax

numpy.can_cast(from_, to, casting='safe')

Parameter value

The numpy.can_cast() function takes the following parameter values:

  • from_: This represents the data type, scalar, or the array to cast from.
  • to: This represents the data type, scalar, or the array to cast to.
  • casting: This controls what kind of data casting is likely to occur. This parameter is optional.

Return value

The numpy.can_cast() function returns a Boolean value. It returns True if the casting can occur and False if it cannot.

Code example

import numpy as np
# casting 32 bit int to 64 bit int data type
a = np.can_cast(np.int32, np.int64)
# casting a 64 bit float to a complex data type
b = np.can_cast(np.float64, complex)
# casting a complex to a float data type
c = np.can_cast(complex, float)
print(a)
print(b)
print(c)

Code explanation

  • Line 1: We import the numpy module.
  • Line 4: We use the np.can_cast() function to check if we can cast from an int32 data type to an int64 data type. The Boolean value is assigned to a variable a.
  • Line 7: We use the np.can_cast() function to check if we can cast from a float64 data type to a complex data type. The Boolean value is assigned to a variable b.
  • Line 10: We use the np.can_cast() function to check if we can cast from a complex data type to a float data type. The Boolean value is assigned to a variable c.
  • Lines 12-14: We print the a, b, and c variables that contain the Boolean values.

Free Resources