w3resource

NumPy: Change the data type of an array

NumPy: Array Object Exercise-39 with Solution

Write a NumPy program to change an array's data type.

Sample Solution:

Python Code:

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

# Creating a NumPy array 'x' with specified data type 'int32'
x = np.array([[2, 4, 6], [6, 8, 10]], np.int32)

# Printing the array 'x'
print(x)

# Printing the data type of array 'x'
print("Data type of the array x is:", x.dtype)

# Changing the data type of array 'x' to 'float'
y = x.astype(float)

# Printing the new data type of array 'y'
print("New Type: ", y.dtype)

# Printing the modified array 'y' with the new data type
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.]]

Explanation:

In the above exercise -

x = np.array([[2, 4, 6], [6, 8, 10]], np.int32): The current line creates a two-dimensional NumPy array ‘x’ with the specified elements and data type np.int32.

print("Data type of the array x is:",x.dtype): The current line prints the data type of the ‘x’ array, which is int32.

y = x.astype(float): The current line creates a new array ‘y’ by changing the data type of ‘x’ to float. The astype() function is used for this purpose.

print("New Type: ",y.dtype): The current line prints the data type of the new ‘y’ array, which is float64 (the default float data type).

print(y): The current line prints the ‘y’ array with the same elements as ‘x’ but with the new data type float64.

Python-Numpy Code Editor:

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 Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-39.php