Change data type of given numpy array


The Numpy array support a great variety of data types in addition to python's native data types. After an array is created, we can still modify the data type of the elements in the array, depending on our need. The two methods used for this purpose are array.dtype and array.astype

array.dtype

This method gives us the existing data type of the elements in the array. In the below example we declare an array and find its data types.

Example

 Live Demo

import numpy as np
# Create a numpy array
a = np.array([21.23, 13.1, 52.1, 8, 255])
# Print the array
print(a)
# Print the array dat type
print(a.dtype)

Output

Running the above code gives us the following result −

[ 21.23 13.1 52.1 8. 255. ]
float64

array.astype

This method converts the existing array to a new array with desired data types.In the below example we take the given array and convert it to a variety of target data types.

Example

 Live Demo

import numpy as np
# Create a numpy array
a = np.array([21.23, 13.1, 52.1, 8, 255])
# Print the array
print(a)
# Print the array dat type
print(a.dtype)
# Convert the array data type to int32
a_int = a.astype('int32')
print(a_int)
print(a_int.dtype)
# Convert the array data type to str
a_str = a.astype('str')
print(a_str)
print(a_str.dtype)
# Convert the array data type to complex
a_cmplx = a.astype('complex64')
print(a_cmplx)
print(a_cmplx.dtype)

Output

Running the above code gives us the following result −

[ 21.23 13.1 52.1 8. 255. ]
float64
[ 21 13 52 8 255]
int32
['21.23' '13.1' '52.1' '8.0' '255.0']
<U32
[ 21.23+0.j 13.1 +0.j 52.1 +0.j 8. +0.j 255. +0.j]
complex64
raja
Published on 23-Aug-2019 15:05:13
Advertisements