Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Boolean Indexing | Indexing and Slicing
Ultimate NumPy
course content

Contenido del Curso

Ultimate NumPy

Ultimate NumPy

1. NumPy Basics
2. Indexing and Slicing
3. Commonly used NumPy Functions
4. Math with NumPy

book
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.

123456
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)
copy

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):

1234
import numpy as np # Creating an array of integers from 1 to 10 inclusive array = np.arange(1, 11) print(array[array > 5])
copy
You are given an array representing daily temperatures (in °C) for a week. Which of the following retrieves all temperatures greater than 25°C?

You are given an array representing daily temperatures (in °C) for a week. Which of the following retrieves all temperatures greater than 25°C?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 6
We're sorry to hear that something went wrong. What happened?
some-alt