Convert a NumPy Array to 0 or 1 Array Based on Threshold Condition

By | October 18, 2024

A numpy array with 0, 1 elements (also called mask array) can be used to mask some elements in a new array. This trick is very useful when we are operating numpy array.

In this tutorial, we will introduce how to convert and create a numpy mask array based on a given array.

Convert a NumPy Array to 0 or 1 Array Based on Threshold Condition

numpy.where()

We will use numpy.where()

function get this mask array.

It is defined as:

numpy.where(condition, [x, y, ]/)

When condition is True, it will return x, otherwise, return y.

Create a msk array based on threshold value

if x and y is scalar

Example 1:

import numpy as np

x1 = np.array(range(16))
x1 = x1.reshape([4,4])
print("x1=",x1)

y1 = np.where(x1<=4, 1, 0)
print(y1)

It outputs:

x1= [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
y1= [[1 1 1 1]
 [1 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]

In this example, all elements that are bigger than 4 will be assigned to 0, others are assigned to 1.

Example 2:

y2 = np.where(np.logical_and(x>=4, x<=8), 1, 0)
print("y2=", y2)

It outputs:

y2= [[0 0 0 0]
 [1 1 1 1]
 [1 0 0 0]
 [0 0 0 0]]

In this exampe, elemens in x1 are in [4, 8] will be assigned to 1.

If x and y are numpy array.

import numpy as np

x1 = np.array(range(16))
x1 = x1.reshape([4,4])
print("x1=",x1)

x_mask = x1*3
y_mask = x1*-3

y1 = np.where(x1<=4, x_mask, y_mask)
print("y1=",y1)

y2 = np.where(np.logical_and(x1>=4, x1<=8), x_mask, y_mask)
print("y2=", y2)

It outputs:

x1= [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
y1= [[  0   3   6   9]
 [ 12 -15 -18 -21]
 [-24 -27 -30 -33]
 [-36 -39 -42 -45]]
y2= [[  0  -3  -6  -9]
 [ 12  15  18  21]
 [ 24 -27 -30 -33]
 [-36 -39 -42 -45]]

In this exampe, the shapes of  x_mask and y_mask are same to x1.

You can use numpy.where() to get y1 and y2 mask array based on different condition.

Moreover, if you do not use numpy.where(), you can read:

Convert Boolean to 0 and 1 in NumPy

Leave a Reply