Зміст курсу
Ultimate NumPy
Ultimate NumPy
Boolean Indexing
Boolean indexing (also known as boolean array indexing) allows us to select elements in an array based on certain conditions. This type of indexing is extremely useful for efficiently filtering data in arrays, especially in large ones.
Boolean Arrays
To understand how boolean indexing works, we first need to understand what boolean arrays are.
Such an array can be created either by explicitly specifying its elements or based on a certain condition for the elements of a particular array.
Let's look at an example:
import numpy as np # Creating an array of integers from 1 to 10 inclusive array = np.arange(1, 11) # Creating a boolean array based on a condition boolean_array = array > 5 print(boolean_array)
Here, array
is an array of integers from 1
to 10
inclusive. We then create a boolean array named boolean_array
based on the condition array > 5
. This means that if a certain element of array
is greater than 5
(condition is True
), the element in boolean_array
at this index is True
; otherwise, it is False
.
Here is an image to clarify this:
The upper array is our initial array where green elements don’t match the condition, and purple elements match the condition. The lower array is our created boolean array.
Boolean Array Indexing
Boolean indexing works quite straightforwardly: you simply specify the boolean array in square brackets. The resulting elements are those with the indices corresponding to the elements with True
values in the boolean array.
Back to our previous example:
You can see that elements with True
values have indices from 5
to 9
, so the elements of array
with these indices are returned as a result of boolean indexing:
import numpy as np # Creating an array of integers from 1 to 10 inclusive array = np.arange(1, 11) print(array[array > 5])
Дякуємо за ваш відгук!