Convert NumPy Array Float to Int: A Step Guide – NumPy Tutorial

By | September 26, 2022

Sometimes, we often need to convert a float numpy array to int. In this tutorial, we will use an example to show you how to convert.


We can create a numpy array first.

import numpy as np

x = np.random.randn(2,3)

print(x, x.dtype)

Run this code, we will see:

[[ 0.51911853  0.17307953 -0.6802194 ]
 [ 0.01775087  1.0472713  -0.19478363]] float64

It means the x is float64, it is a float array.

How to convert float numpy array to int?

We can use array.astype() to do.

For example:

y = x.astype(np.int16)
print(y, y.dtype)

Run this code, we will see y is an integer numpy array.

[[0 0 0]
 [0 1 0]] int16

Meanwhile, we also can use it to convert a boolean array to int.

Convert Boolean to 0 and 1 in NumPy – NumPy Tutorial