Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Return True if cast between data types can occur according to the casting rule in Python
The numpy.can_cast() method returns True if a cast between data types can occur according to NumPy's casting rules. It takes two parameters: the source data type and the target data type to cast to.
Syntax
numpy.can_cast(from_dtype, to_dtype, casting='safe')
Parameters
from_dtype: The data type or array to cast from
to_dtype: The data type to cast to
casting: Controls what kind of data casting may occur ('no', 'equiv', 'safe', 'same_kind', 'unsafe')
Basic Usage
Let's check if various data type conversions are possible ?
import numpy as np
print("Checking with can_cast() method in NumPy\n")
print("int32 to int64:", np.can_cast(np.int32, np.int64))
print("float64 to complex:", np.can_cast(np.float64, complex))
print("complex to float:", np.can_cast(complex, float))
print("int64 to float64:", np.can_cast('i8', 'f8'))
print("int64 to float32:", np.can_cast('i8', 'f4'))
print("int32 to string:", np.can_cast('i4', 'S4'))
Checking with can_cast() method in NumPy int32 to int64: True float64 to complex: True complex to float: False int64 to float64: True int64 to float32: False int32 to string: False
Understanding the Results
The method follows NumPy's casting hierarchy:
- int32 to int64: Safe upcast (smaller to larger integer)
- float64 to complex: Safe conversion (real numbers can become complex)
- complex to float: Unsafe (would lose imaginary part)
- int64 to float32: Unsafe (potential precision loss)
Using Different Casting Rules
import numpy as np
# Safe casting (default)
print("Safe casting:")
print("int64 to float32 (safe):", np.can_cast('i8', 'f4', casting='safe'))
# Same kind casting
print("\nSame kind casting:")
print("int64 to float32 (same_kind):", np.can_cast('i8', 'f4', casting='same_kind'))
# Unsafe casting
print("\nUnsafe casting:")
print("int64 to float32 (unsafe):", np.can_cast('i8', 'f4', casting='unsafe'))
Safe casting: int64 to float32 (safe): False Same kind casting: int64 to float32 (same_kind): True Unsafe casting: int64 to float32 (unsafe): True
Conclusion
The numpy.can_cast() method helps determine if data type conversions are safe according to NumPy's casting rules. Use it to prevent data loss when converting between different numeric types in your arrays.
Advertisements
