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
Return a scalar type which is common to the input arrays in Python
To return a scalar type which is common to the input arrays, use the numpy.common_type() method in Python NumPy. This method finds the most appropriate data type that can represent all input arrays without losing precision. The return type will always be an inexact (i.e. floating point) scalar type, even if all the arrays are integer arrays.
All input arrays except int64 and uint64 can be safely cast to the returned dtype without loss of information. If one of the inputs is an integer array, the minimum precision type returned is a 64-bit floating point dtype.
Syntax
numpy.common_type(*arrays)
Parameters
- arrays ? Input arrays or data types to find common type for
Examples
Basic Usage
Let's start with simple examples to understand how common_type() works ?
import numpy as np
# Single float32 array
result1 = np.common_type(np.arange(3, dtype=np.float32))
print("Float32 array:", result1)
# Mixed float32 and int array
result2 = np.common_type(np.arange(3, dtype=np.float32), np.arange(2))
print("Float32 + int arrays:", result2)
Float32 array: <class 'numpy.float32'> Float32 + int arrays: <class 'numpy.float64'>
Complex and Mixed Types
When complex numbers are involved, the common type becomes complex128 ?
import numpy as np
# With complex numbers
result3 = np.common_type(np.arange(3), np.array([22, 2j]), np.array([32.9]))
print("With complex:", result3)
# Multiple integer and float arrays
result4 = np.common_type(np.arange(3), np.array([22, 39]), np.array([32.9]))
print("Int + float arrays:", result4)
# Different integer types
result5 = np.common_type(np.arange(3, dtype=np.int32), np.arange(2))
print("Int32 + int arrays:", result5)
With complex: <class 'numpy.complex128'> Int + float arrays: <class 'numpy.float64'> Int32 + int arrays: <class 'numpy.float64'>
Key Points
- Always returns floating point or complex types, never integer types
- When integers are mixed, minimum return type is
float64 - Complex numbers result in
complex128type - Preserves precision by choosing the most appropriate common type
Conclusion
The numpy.common_type() method is useful for determining a safe common data type when working with multiple arrays of different types. It ensures data integrity by always returning floating point or complex types that can accommodate all input arrays.
