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.
Next, let's learn about Fancy Indexing in NumPy
, a tool for accessing multiple non-adjacent array items. We pass an array of indices to select these items.
Consider an array of seven numbers:
We fetch the 1st, 3rd, and 5th elements together:
Let's consider a practical use of Fancy Indexing. Given an array representing people's ages, we want to fetch the ages of person 2, person 5, and person 7:
We've covered Boolean Indexing and Fancy Indexing in NumPy
in today's session, moving from the basics to a more powerful, combined application of the methods.
Now it's your turn to put these techniques into practice. The following exercises will allow you to refine your skills and solidify the concepts learned. Happy coding!
