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
Determine common type following standard coercion rules in Python
In NumPy, find_common_type() determines the common data type following standard coercion rules. This function helps when working with mixed data types in arrays and scalars, returning the most appropriate common type.
Syntax
numpy.find_common_type(array_types, scalar_types)
Parameters
The function takes two parameters:
- array_types − A list of dtypes or dtype convertible objects representing arrays
- scalar_types − A list of dtypes or dtype convertible objects representing scalars
How It Works
The method returns the common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned.
Example
Let's explore various combinations of array and scalar types ?
import numpy as np
print("Using the find_common_type() method in NumPy\n")
# Float32 array with int64 and float64 scalars
result1 = np.find_common_type([np.float32], [np.int64, np.float64])
print("Float32 array with int64/float64 scalars:", result1)
# Empty array types with mixed scalars
result2 = np.find_common_type([], [np.int64, np.float32, complex])
print("Empty array with mixed scalars:", result2)
# Float32 array with complex scalar
result3 = np.find_common_type([np.float32], [complex])
print("Float32 array with complex scalar:", result3)
# Float64 array with complex scalar
result4 = np.find_common_type([np.float64], [complex])
print("Float64 array with complex scalar:", result4)
# String dtype representations
result5 = np.find_common_type(['f4', 'i4'], ['c8'])
print("String dtypes f4/i4 arrays with c8 scalar:", result5)
# Integer array with float scalar
result6 = np.find_common_type([np.int64], [np.float64])
print("Int64 array with float64 scalar:", result6)
Using the find_common_type() method in NumPy Float32 array with int64/float64 scalars: float32 Empty array with mixed scalars: complex128 Float32 array with complex scalar: complex128 Float64 array with complex scalar: complex128 String dtypes f4/i4 arrays with c8 scalar: complex128 Int64 array with float64 scalar: float64
Key Points
- Array types take precedence over scalar types in determining the common type
- When array types are empty, the function considers only scalar types
- Complex types generally dominate other numeric types
- The function follows NumPy's standard type promotion rules
Conclusion
The find_common_type() function is essential for determining compatible data types when working with mixed NumPy arrays and scalars. It follows standard coercion rules to ensure type safety in numerical computations.
