How to change data type of a given NumPy array?

astype() function is used to change the data type of a given array. This function takes data type as an argument in which you want to change array.

Syntax of numpy.ndarray.astype()

numpy.ndarray.astype(dtype)

dtype parameter is used to specify the data type in which you want to change the given Numpy array.

Example 1: Here, we will change the data type of array from int64 to float64.

import numpy as np

x = np.array([12, 24, 36, 48])
print('Array a:', x)
print('Data type of array a:', x.dtype)
x = x.astype('float64')
print('Data type of array a after calling astype():', x.dtype)
print('Array a:', x)

Output of the above program

Array a: [12 24 36 48]
Data type of array a: int64
Data type of array a after calling astype(): float64
Array a: [12. 24. 36. 48.]

Example 2: In this example, we will change the data type of array from float64 to complex128

import numpy as np

x = np.array([1.2, 2.04, 36.65, 48])
print('Array a:', x)
print('Data type of array a:', x.dtype)
x = x.astype('complex128')
print('Data type of array a after calling astype():', x.dtype)
print('Array a:', x)

Output of the above program

Array a: [ 1.2   2.04 36.65 48.  ]
Data type of array a: float64
Data type of array a after calling astype(): complex128
Array a: [ 1.2 +0.j  2.04+0.j 36.65+0.j 48.  +0.j]

Recommended Posts