Advanced Indexing: Filtering and Selecting Intelligently
7 min read
Welcome back! So far, you've mastered the basics of creating NumPy arrays and accessing their elements one by one or in simple slices. That's like knowing how to pick a single book off a shelf or grab a whole row.
But what if your task is more complex? What if you need to grab the 3rd, 7th, and 21st book all at once? Or what if you need to find all the books with more than 500 pages, but you don't know where they are on the shelves?
This is the world of advanced indexing. It's about moving beyond simple slices and learning to select and filter data with precision and intelligence. Let's get started!
1. Fancy Indexing: Selecting Multiple Specific Elements π―
The Problem: Imagine you have a large dataset of sensor readings, and you need to pull out the readings from specific, non-sequential time points (e.g., the 5th, 18th, and 42nd reading). Using a simple slice like data[5:42] won't work because that would give you everything between those points.
The Solution: Fancy Indexing
Fancy indexing is the fancy term for passing an array of indices to access multiple array elements at once. Instead of one number, you give it a list or an array of all the numbers you want.
Let's see it in action.
Example: 1D Array
First, let's create a simple array. Imagine this is a list of product prices, and the index is the product ID.
import numpy as np
# Product prices for IDs 0 through 9
prices = np.array([10.5, 22.0, 8.75, 15.0, 30.2, 5.5, 12.8, 45.1, 19.9, 25.0])
# We want to get the prices for product IDs 2, 5, and 8
specific_ids = [2, 5, 8]
# Use fancy indexing to get them!
specific_prices = prices[specific_ids]
print(specific_prices)
# Output: [ 8.75 5.5 19.9 ]Boom! π₯ Just like that, you've picked out exactly the elements you needed, no loops required.
Example: 2D Array
Fancy indexing gets even more powerful with multi-dimensional arrays. Imagine a 2D array representing a tic-tac-toe board.
# 0 = empty, 1 = 'X', 2 = 'O'
board = np.array([[1, 2, 0],
[0, 1, 2],
[1, 0, 2]])
# Let's get the elements at row 0, col 1 and row 2, col 2
rows = np.array([0, 2])
cols = np.array([1, 2])
# Pass the row and col arrays to get the specific elements
elements = board[rows, cols]
print(elements)
# Output: [2 2]This selected the element at (0, 1) and the element at (2, 2).
β¨ Fun Fact: When you use fancy indexing, NumPy returns a copy of the data, not a view. This is a crucial difference from basic slicing. If you change the new array, the original array will not change. This prevents you from accidentally modifying your source data, which is a very good thing!
2. Boolean Indexing: Filtering with Conditional Masks π
The Problem: Now, imagine a different scenario. You have that same array of product prices, but this time your goal is to find all prices that are greater than $20. You don't know their indices beforehand. How do you "ask" the array to give you only the elements that meet this condition?
The Solution: Boolean Masks
Boolean indexing (or filtering) is a technique where you use a boolean array (an array of True and False values) to select elements from another array. This boolean array acts as a "mask". The original array "wears" this mask, and only the elements corresponding to a True value are visible.
How it Works: A Two-Step Process
- Create the Condition: You first write a condition that NumPy applies to every element in your array. This operation returns a new boolean array.
- Apply the Mask: You then use this new boolean array as the index for your original array.
Let's try it with our prices.
import numpy as np
prices = np.array([10.5, 22.0, 8.75, 15.0, 30.2, 5.5, 12.8, 45.1, 19.9, 25.0])
# Step 1: Create the condition
# "Is the price greater than 20?"
is_expensive_mask = prices > 20.0
print("The Boolean Mask:")
print(is_expensive_mask)
# Output: [False True False False True False False True False True]
# Step 2: Apply the mask to the original array
expensive_prices = prices[is_expensive_mask]
print("\nExpensive Prices:")
print(expensive_prices)
# Output: [22. 30.2 45.1 25. ]See what happened? NumPy returned only the numbers from the prices array where the is_expensive_mask had a True value. This is the fundamental technique for data filtering in Python and is used everywhere in libraries like Pandas.
3. Combining Conditions: The & (AND) and | (OR) Operators π€
The Problem: Your filtering needs are getting more complex. You don't just want prices over 10 AND less than $30**. How do you combine these two conditions?
The Solution: Bitwise Operators (&, |)
You can't use Python's regular and and or keywords here. Those keywords are designed to work with single boolean values (e.g., True and False), not entire boolean arrays.
Instead, NumPy uses the bitwise operators & for AND and | for OR.
π¨ Important: When combining conditions, you must wrap each condition in parentheses () due to Python's operator precedence rules. Forget this, and you'll be greeted with a confusing ValueError.
Example: Combining with & (AND)
Let's find those prices between 30.
import numpy as np
prices = np.array([10.5, 22.0, 8.75, 15.0, 30.2, 5.5, 12.8, 45.1, 19.9, 25.0])
# Condition 1: prices > 10
# Condition 2: prices < 30
# Note the parentheses around each condition!
mask = (prices > 10) & (prices < 30)
print("Combined Mask:")
print(mask)
# Output: [ True True False True False False True False True True]
print("\nPrices between $10 and $30:")
print(prices[mask])
# Output: [10.5 22. 15. 12.8 19.9 25. ]Example: Combining with | (OR)
Now, let's find prices that are either very cheap (less than 40).
# Using the same prices array
mask_or = (prices < 10) | (prices > 40)
print("OR Mask:")
print(mask_or)
# Output: [False False True False False True False True False False]
print("\nCheap or Expensive Prices:")
print(prices[mask_or])
# Output: [ 8.75 5.5 45.1 ]Think of the parentheses as little hugs for your conditions to keep them safe and sound before they are combined. π€
4. Conditional Logic Simplified: Mastering np.where() β
The Problem: Filtering is great for selecting data. But what if you want to create a new array based on a condition? For example, you want to create a new array that contains the word "High" if the price is over $20, and "Low" otherwise. A standard if/else in a for loop would be slow.
The Solution: np.where()
The np.where() function is the NumPy way of expressing if-else logic across an entire array, and it's incredibly fast.
The structure is simple: np.where(condition, value_if_true, value_if_false)
Example: Categorizing Prices
Let's implement our "High"/"Low" price category idea.
import numpy as np
prices = np.array([10.5, 22.0, 8.75, 15.0, 30.2, 5.5, 12.8, 45.1, 19.9, 25.0])
# Condition: Is the price > 20?
# If True, use the string 'High'
# If False, use the string 'Low'
price_categories = np.where(prices > 20, 'High', 'Low')
print(price_categories)
# Output: ['Low' 'High' 'Low' 'Low' 'High' 'Low' 'Low' 'High' 'Low' 'High']Example: Conditional Replacement
Another common use case is to replace certain values. Let's say we want to replace all prices below 10.
# Condition: Is the price < 10?
# If True, replace it with 10.0
# If False, keep the original price
adjusted_prices = np.where(prices < 10, 10.0, prices)
print(adjusted_prices)
# Output: [10.5 22. 10. 15. 30.2 10. 12.8 45.1 19.9 25. ]np.where() is a powerful tool for data cleaning, transformation, and feature engineering, all without writing slow Python loops. It's a cornerstone of efficient, vectorized programming in NumPy.
Further Reading and References
To dive even deeper, check out the official documentation. It's the ultimate source of truth!
- Official NumPy Documentation on Indexing: NumPy Indexing Guide
- W3Schools NumPy Where Tutorial: W3Schools `np.where`
Challenge
You are given a 2D NumPy array named inventory_data representing product information. Each row corresponds to a product, and the columns are [product_ID, price, units_sold, stock_level].
Your task is to perform a series of data manipulation operations using advanced indexing techniques.
A marketing campaign is planned for products located at indices
2,5, and8. Use fancy indexing to create a new array calledcampaign_productscontaining the complete data for only these specific products.Identify products that are underperforming but have high stock. Create a boolean mask named
stagnant_maskfor products whereunits_soldis less than20ANDstock_levelis greater than150. Then, use this mask to create an array namedstagnant_productscontaining the data for these items.Create a new 1D array called
price_categories. This array must have the same length as the number of products. Usingnp.where(), categorize each product's price. The value should be"High"if its price is greater than50,"Low"if the price is less than20, and"Mid"for all other cases.Management has decided to apply a 5% price increase for products with low availability. Create a new 1D array called
updated_priceswhich contains the original prices, but with the 5% increase applied only to products where thestock_levelis below10. Do not modify the originalinventory_dataarray.
Expected result
Your code should correctly define four variables: campaign_products, stagnant_products, price_categories, and updated_prices.
campaign_products: A 2D NumPy array with a shape of(3, 4). It should contain the complete rows for the products at indices 2, 5, and 8 from the originalinventory_data.stagnant_products: A 2D NumPy array containing the rows for products that meet both conditions:units_sold < 20ANDstock_level > 150. For the given data, this array should have a shape of(2, 4).price_categories: A 1D NumPy array with 10 string elements. The expected output is['Low', 'High', 'Mid', 'High', 'Low', 'High', 'Low', 'Mid', 'High', 'Mid'].updated_prices: A 1D NumPy array with 10 float elements. It should contain the original prices, except for products withstock_level < 10(at indices 3 and 8), whose prices should be increased by 5%. The new prices for these items should be approximately104.99and94.40.