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:

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:

Practice with Boolean Indexing: Selecting 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.

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:

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.

Introduction to Fancy Indexing

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:

Practice with Fancy Indexing

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:

Lesson Summary

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!

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