Introduction to Boolean Indexing

Hello! We'll explore a concept called Boolean Indexing in NumPy today. It lets us access array elements based on conditions instead of explicit indices.

Practice with Boolean Indexing: Dataset

To illustrate, let's create a NumPy array, data:

import numpy as np

data = np.array([12, 43, 36, 32, 51, 18, 79, 7])
print("Data: ", data)  # Data:  [12 43 36 32 51 18 79  7]
Practice with Boolean Indexing: Boolean Mask

Now, suppose we want to extract elements greater than 30. We form a Boolean array checking this condition for data:

bool_array = data > 30
print("Boolean Array: ", bool_array)  # Boolean Array:  [False  True  True  True  True False  True False]
Practice with Boolean Indexing: Selecting Data

To extract the elements that satisfy our condition from data, we use the bool_array as an index:

filtered_data = data[bool_array]
print("Filtered Data: ", filtered_data)  # Filtered Data:  [43 36 32 51 79]

Now filtered_data only holds values from data that are greater than 30.

Complex Filter Condition

We can also use Boolean conditions to combine multiple criteria using logical operators like & for AND and | for OR.

Consider an array of prices per unit for different products in a retail store:

prices = np.array([15, 30, 45, 10, 20, 35, 50])
print("Prices: ", prices)  # Prices:  [15 30 45 10 20 35 50]

Suppose we want to find prices that are greater than 20 and less than 40. We can combine conditions using the & operator:

filtered_prices = prices[(prices > 20) & (prices < 40)]
print("Filtered Prices (20 < price < 40): ", filtered_prices)  
# Filtered Prices (20 < price < 40):  [30 35]

Now, let's consider finding prices that are either less than 15 or greater than 45 using the | operator:

filtered_prices_or = prices[(prices < 15) | (prices > 45)]
print("Filtered Prices (price < 15 OR price > 45): ", filtered_prices_or) 
# Filtered Prices (price < 15 OR price > 45):  [10 50]

Using these logical operators, you can create complex filtering conditions to extract exactly the data you need.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal