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

Зміст курсу

Ultimate NumPy

Ultimate NumPy

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

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

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.

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:

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

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 7
We're sorry to hear that something went wrong. What happened?
some-alt