Convert Boolean to 0 and 1 in NumPy – NumPy Tutorial

By | August 16, 2022

Sometimes, we need convert a boolean array to 0 and 1. In this tutorial, we will introduce you how to do.

For example:

False == 0

True == 1

import numpy as np
mask = np.arange(1,16)
x = 10
t = mask<=x
print(t)
d = t.astype(int)
print(d)

In this example, t is:

[ True  True  True  True  True  True  True  True  True  True False False
 False False False]

Then we can use t.astype(int) to convert it to int 0 and 1.

Then, we can find d is:

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

Leave a Reply