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.
To illustrate, let's create a NumPy array, data:
Now, suppose we want to extract elements greater than 30. We form a Boolean array checking this condition for data:
To extract the elements that satisfy our condition from data, we use the bool_array as an index:
Now filtered_data only holds values from data that are greater than 30.
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:
Suppose we want to find prices that are greater than 20 and less than 40. We can combine conditions using the & operator:
Now, let's consider finding prices that are either less than 15 or greater than 45 using the | operator:
Using these logical operators, you can create complex filtering conditions to extract exactly the data you need.
