w3resource

NumPy: Convert numpy dtypes to native python types


Convert NumPy Dtypes to Python Types

Write a NumPy program to convert numpy dtypes to native Python types

This problem involves writing a NumPy program to convert NumPy data types (dtypes) to native Python types. The task requires using NumPy's type conversion functions to transform NumPy-specific data types, such as numpy.int32 or numpy.float32, into their equivalent native Python types, like int or float. This process ensures compatibility between NumPy arrays and standard Python operations by enabling seamless data type conversions.

Sample Solution :

Python Code :

# Importing the NumPy library with an alias 'np'
import numpy as np

# Printing a message indicating conversion from numpy.float32 to Python float
print("numpy.float32 to python float")

# Creating a numpy.float32 value 'x' initialized to 0
x = np.float32(0)

# Printing the type of 'x'
print(type(x))

# Extracting the Python float value from the numpy.float32 'x' using the item() method
pyval = x.item()

# Printing the type of the extracted Python float value 'pyval'
print(type(pyval)) 

Output:

numpy.float32 to python float
<class 'numpy.float32'>
<class 'float'>

Explanation:

In the above code -

np.float32(0) creates a NumPy scalar of data type float32 stores in the variable 'x' and initializes it with the value 0.

print(type(x)) prints the type of 'x', which is a NumPy scalar type: .

The x.item() statement converts the NumPy scalar 'x' to a Python native type using the 'item()' method. In this case, the Python native type is 'float'. The result is stored in the variable 'pyval'.

The print(type(pyval)) statement prints the type of 'pyval', which is a Python native type: .

Python-Numpy Code Editor: