How to Use the Numpy astype() Function in Python

09/15/2021

Contents

In this article, you will learn how to use the Numpy astype() function in Python.

Numpy astype() Function

The astype() function in NumPy is used to cast a given array to a specified data type. It returns a new array with the specified data type.

Syntax

The syntax for using the astype() function is as follows:

numpy.astype(arr, dtype, order='K', casting='unsafe', subok=True, copy=True)
Parameters

Here is an explanation of the parameters:

  • arr: The input array that you want to cast to a new data type.
  • dtype: The data type to which you want to cast the input array.
  • order: Specifies the order in which the array data is stored in memory. It defaults to ‘K’ which means that the memory order is kept the same as the input array.
  • casting: Specifies the casting rule to be used when casting the array to a new data type. It defaults to ‘unsafe’ which means that no checking is done to ensure that the cast is safe.
  • subok: Specifies whether to return a subclass of the input array if possible. It defaults to True, which means that a subclass will be returned if possible.
  • copy: Specifies whether to create a new copy of the input array. It defaults to True, which means that a new copy will be created.
Example

Here is an example usage of the astype() function:

import numpy as np

# create an array of integers
a = np.array([1, 2, 3, 4, 5])

# cast the array to float data type
b = a.astype(float)

# print the original and the new arrays
print(a)
print(b)

# Output:
# [1 2 3 4 5]
# [1. 2. 3. 4. 5.]

In this example, we created an array a containing integers, and then we used the astype() function to cast it to the float data type. The resulting array b contains the same values as a, but with the data type changed to float.