Conteúdo do Curso
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.
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
.
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.
You can see that the elements with True
values have indices from 5
to 9
. As a result, the elements of the array
at these indices are returned through boolean indexing (the picture above corresponds to this code):
import numpy as np # Creating an array of integers from 1 to 10 inclusive array = np.arange(1, 11) print(array[array > 5])
Obrigado pelo seu feedback!