Return the data type with the smallest size and scalar kind to which both the given types be safely cast in Python

The numpy.promote_types() method returns the data type with the smallest size and scalar kind to which both given types can be safely cast. This is useful when you need to determine the appropriate data type for operations involving mixed types.

Syntax

numpy.promote_types(type1, type2)

Parameters

type1: First data type (string or numpy dtype)
type2: Second data type (string or numpy dtype)

Return Value

Returns the promoted data type that can safely hold values from both input types. The returned data type is always in native byte order.

Basic Examples

Let's start by importing NumPy and exploring basic type promotion ?

import numpy as np

# Float type promotion
print("f4 + f8 =", np.promote_types('f4', 'f8'))

# Integer to float promotion  
print("i8 + f4 =", np.promote_types('i8', 'f4'))

# Complex type promotion
print("i8 + c8 =", np.promote_types('>i8', '<c8'))
f4 + f8 = float64
i8 + f4 = float64
i8 + c8 = complex128

Using NumPy Data Types

You can also use NumPy data type objects instead of string representations ?

import numpy as np

# Using NumPy dtype objects
print("int32 + int64 =", np.promote_types(np.int32, np.int64))
print("float64 + complex =", np.promote_types(np.float64, complex))
print("complex + float =", np.promote_types(complex, float))
int32 + int64 = int64
float64 + complex = complex128
complex + float = complex128

String and Mixed Type Promotion

When mixing numeric types with strings, the result accommodates both ?

import numpy as np

# String and integer promotion
print("i4 + S8 =", np.promote_types('i4', 'S8'))

# Different endianness handling
print("Big-endian i8 + Little-endian c8 =", np.promote_types('>i8', '<c8'))
i4 + S8 = |S11
Big-endian i8 + Little-endian c8 = complex128

Common Type Promotion Rules

Type 1 Type 2 Promoted Type
int float float
float complex complex
smaller int larger int larger int
numeric string string (enlarged)

Conclusion

The numpy.promote_types() function helps determine safe data types for mixed-type operations. It follows NumPy's type promotion hierarchy, ensuring no data loss during type conversion.

Updated on: 2026-03-26T19:20:32+05:30

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements