w3resource

NumPy: Change the data type of an array

NumPy: Array Object Exercise-39 with Solution

Write a NumPy program to change the data type of an array.

Sample Solution:-

Python Code:

import numpy as np
x = np.array([[2, 4, 6], [6, 8, 10]], np.int32)
print(x)
print("Data type of the array x is:",x.dtype)
# Change the data type of x
y = x.astype(float)
print("New Type: ",y.dtype)
print(y)

Sample Output:

[[ 2  4  6]                                                            
 [ 6  8 10]]                                                           
Data type of the array x is: int32                                     
New Type:  float64                                                     
[[  2.   4.   6.]                                                      
 [  6.   8.  10.]]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to create a new shape to an array without changing its data.
Next: Write a NumPy program to create a new array of 3*5, filled with 2.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}