NumPy

Updating NumPy array elements and Boolean Indexing

In this tutorial, you will learn how to change the values of NumPy array elements and to filter and conditionally update values using Boolean Indexing.


Let's create a new 2D array:

Python

If you need to update a specific element in a NumPy array, you can use direct assignment.

Here, we index the element in the 2nd row and 3rd column and assign a new value:

Python
Output

An amazing feature of NumPy is the ability to update values conditionally using Boolean Indexing.

Boolean Indexing allows you to select elements from an array based on conditions.

To do so, you first have to create a Boolean array by applying a condition to a NumPy array.

For example, here the condition we apply to our array is that elements should be less than 5:

Python
Output

As you can see, we get an array of Booleans that has the same shape as the original one.

You then use this Boolean array to index the original array. Only the elements where the Boolean array is True will be selected.

This way, you can filter elements from an array:

Python
Output

But, you can also assign new values to those elements where the condition is True

Let's update all values that are less than 5:

Python
Output

Instead of doing it in 2 steps, we can index and apply the condition at the same time:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

Another way to update multiple elements in a NumPy array is by slicing.

For example, here we update the entire first row using slicing:

Python
Output

Or the first 2 rows and first 2 columns:

Python
Output

Ensure that the shape of the array you assign matches the shape of the selected slice.

Here, we attempt to assign a 1D array to a 2D slice. Let's see what happens:

Python
Output

What will be the output?

Python