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:
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:
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:
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:
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:
Instead of doing it in 2 steps, we can index and apply the condition at the same time:
What will be the output?
What will be the output?
What will be the output?
Another way to update multiple elements in a NumPy array is by slicing.
For example, here we update the entire first row using slicing:
Or the first 2 rows and first 2 columns:
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:
What will be the output?