w3resource

NumPy: Convert numpy dtypes to native python types

NumPy: Basic Exercise-41 with Solution

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

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)) 

Sample 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:

Previous: NumPy program to compute the x and y coordinates for points on a sine curve and plot the points using matplotlib.
Next: NumPy program to add elements in a matrix. If an element in the matrix is 0, we will not add the element below this element.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.