The Numpy library in Python comes with a number of useful functions and methods to work with and manipulate the data in arrays. In this tutorial, we will look at how to set all the non-zero values in a Numpy array to one with the help of some examples.
Steps to set all non zero values to one in Numpy
You can use boolean indexing to set all the non zero values in a Numpy array to one. The following is the syntax –
# set non-zero values to one ar[ar != 0] = 1
It replaces the non-zero values in the array
Let’s now look at a step-by-step example of using this syntax –
Step 1 – Create a Numpy array
First, we will create a Numpy array that we will use throughout this tutorial.
import numpy as np # create numpy array ar = np.array([-3, -2, -1, 0, 1, 2, 3]) # display the array print(ar)
[-3 -2 -1 0 1 2 3]
Here, we used the
numpy.array() function to create a one-dimensional Numpy array containing some numbers. You can see that the array has both positive and negative values (along with a zero).
Step 2 – Make non-zero values one using boolean indexing
Using boolean indexing identify the values that are not equal to zero and then set them to
First, we will specify our boolean expression
ar != 0 (which finds the non-zero values in the array) and then set values satisfying this condition to one.
# set non-zero values to one ar[ar != 0] = 1 # display the array print(ar)
[1 1 1 0 1 1 1]
The resulting array has all the non-zero values replaced with one.
To understand what’s happening here, let’s look under the hood. Let’s see what we get from the expression
ar != 0
# create a numpy array ar = np.array([-3, -2, -1, 0, 1, 2, 3]) # result of boolean expression ar != 0 ar != 0
array([ True, True, True, False, True, True, True])
We get a boolean array. The boolean values in this array represent whether a value at a particular index satisfies the given condition or not (in our case whether the element is not equal to zero or not).
When we do
ar[ar != 0] = 1, we are essentially setting the values in the array where the condition evaluates to
You can similarly filter a Numpy array for other conditions as well.
Summary – Set non-zero values to
1 in Numpy
In this tutorial, we looked at how to set all the non-zero values in a Numpy array to one. The following is a short summary of the steps mentioned –
- Create a Numpy array (skip this step if you already have an array to operate on).
- Use boolean indexing to find the non-zero values and then set them to one –
ar[ar != 0] = 1
You might also be interested in –
- Numpy – Make All Negative Values Zero in Array
- Numpy Array – Get All Values Smaller than a Given Value
- Filter a Numpy Array – With Examples
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.