Curriculum
Course: NumPy
Login

Curriculum

NumPy

Text lesson

Converting Data Type on Existing Arrays

The most effective way to change the data type of an existing array is to create a copy using the astype() method.

The astype() function generates a copy of the array and allows you to specify the desired data type as a parameter.

You can specify the data type using a string, such as ‘f’ for float or ‘i’ for integer, or by using the data type directly, such as float for float and int for integer.

Example

Change the data type from float to integer by using ‘i’ as the parameter value.

import numpy as np

arr = np.array([1.12.13.1])

newarr = arr.astype(‘i’)

print(newarr)
print(newarr.dtype)

Example

Change the data type from float to integer by using int as the parameter value.

import numpy as np

arr = np.array([1.12.13.1])

newarr = arr.astype(int)

print(newarr)
print(newarr.dtype)

Example

Change the data type from integer to boolean.

import numpy as np

arr = np.array([103])

newarr = arr.astype(bool)

print(newarr)
print(newarr.dtype)