Fancy and Boolean Indexing in NumPy
NumPy provides powerful ways to access array elements using more than just basic integers and slices. With fancy indexing and boolean indexing, you can select data based on specific positions or conditions.
These techniques allow for more advanced and flexible data extraction — perfect for filtering, modifying, or reshaping arrays efficiently.
- Fancy Indexing: Use arrays or lists of indices to access multiple elements at once.
- Boolean Indexing: Use boolean conditions to filter elements that meet specific criteria.
Fancy Indexing in NumPy
Fancy indexing lets you access multiple array elements at once by using a list or array of indices. Instead of retrieving elements one at a time, you can use an array of indices to get a custom selection.
This is especially useful when you want to reorder, filter, or pick non-contiguous elements from a NumPy array.
Example: Selecting Multiple Elements
Here's how you can use fancy indexing with a 1D array:
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
# Select elements at index 0, 2, and 4
indices = [0, 2, 4]
selected = arr[indices]
print("Selected elements:", selected)
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
# Select elements at index 0, 2, and 4
indices = [0, 2, 4]
selected = arr[indices]
print("Selected elements:", selected)
How It Works:
- indices = [0, 2, 4]: Defines the positions you want to extract.
- arr[indices]: Uses fancy indexing to get those elements.
Output
Selected elements: [10 30 50]
Selected elements: [10 30 50]
Example: Reordering Elements
Fancy indexing can also be used to reorder elements:
arr = np.array([100, 200, 300, 400, 500])
# Reverse order using fancy indexing
reordered = arr[[4, 3, 2, 1, 0]]
print("Reordered:", reordered)
arr = np.array([100, 200, 300, 400, 500])
# Reverse order using fancy indexing
reordered = arr[[4, 3, 2, 1, 0]]
print("Reordered:", reordered)
Output
Reordered: [500 400 300 200 100]
Reordered: [500 400 300 200 100]
💡 Tip: Fancy indexing returns a copy of the selected data — modifying it won't change the original array.
Boolean Indexing in NumPy
Boolean indexing lets you filter elements in a NumPy array using conditional expressions. It creates a boolean array (of True and False) which is then used to select elements where the condition is True.
This is a powerful technique for extracting data that meets specific criteria, such as all values greater than a threshold or equal to a target.
Example: Filtering Values Based on Condition
Let's say you want to extract all scores greater than 70 from an array:
import numpy as np
scores = np.array([65, 82, 90, 45, 76, 55])
# Get all scores greater than 70
high_scores = scores[scores > 70]
print("High scores:", high_scores)
import numpy as np
scores = np.array([65, 82, 90, 45, 76, 55])
# Get all scores greater than 70
high_scores = scores[scores > 70]
print("High scores:", high_scores)
How It Works:
- scores > 70: Returns a boolean array like [False, True, True, False, True, False].
- scores[...]: Filters the array where the condition is True.
Output
High scores: [82 90 76]
High scores: [82 90 76]
Example: Combining Conditions
You can combine multiple conditions using logical operators like & (and), | (or), and ~ (not).
# Get scores between 60 and 80 (inclusive of 60, exclusive of 80)
filtered = scores[(scores >= 60) & (scores < 80)]
print("Scores between 60 and 80:", filtered)
# Get scores between 60 and 80 (inclusive of 60, exclusive of 80)
filtered = scores[(scores >= 60) & (scores < 80)]
print("Scores between 60 and 80:", filtered)
Output
Scores between 60 and 80: [65 76]
Scores between 60 and 80: [65 76]
💡 Tip: Always wrap conditions in parentheses when combining them with logical operators like & or | to avoid precedence errors.
Example 1: Filtering and Selecting Specific Scores
Imagine you have a list of student scores, and you want to:
- Select only the scores greater than 80 (using boolean indexing).
- Pick scores at specific positions (using fancy indexing).
import numpy as np
scores = np.array([72, 85, 91, 60, 88, 77])
# Boolean indexing: scores greater than 80
high_scores = scores[scores > 80]
# Fancy indexing: select scores at index 0, 3, and 5
selected_indices = [0, 3, 5]
selected_scores = scores[selected_indices]
print("High scores (>80):", high_scores)
print("Selected scores:", selected_scores)
import numpy as np
scores = np.array([72, 85, 91, 60, 88, 77])
# Boolean indexing: scores greater than 80
high_scores = scores[scores > 80]
# Fancy indexing: select scores at index 0, 3, and 5
selected_indices = [0, 3, 5]
selected_scores = scores[selected_indices]
print("High scores (>80):", high_scores)
print("Selected scores:", selected_scores)
How It Works:
- scores[scores > 80]: Returns scores greater than 80.
- scores[[0, 3, 5]]: Retrieves scores at specified positions.
Output
High scores (>80): [85 91 88]
Selected scores: [72 60 77]
High scores (>80): [85 91 88]
Selected scores: [72 60 77]
💡 Tip: Fancy indexing and boolean indexing can be used together for powerful filtering and selection logic.
Frequently Asked Questions
What is fancy indexing in NumPy?
What is fancy indexing in NumPy?
Fancy indexing in NumPy allows you to access multiple elements from an array using a list or array of indices. It's useful for reordering or selecting specific elements.
What is boolean indexing in NumPy?
What is boolean indexing in NumPy?
Boolean indexing lets you filter elements in a NumPy array using a boolean condition. It returns the elements where the condition evaluates to True.
How is fancy indexing different from slicing?
How is fancy indexing different from slicing?
Slicing selects continuous blocks of data, while fancy indexing allows non-contiguous selection using lists or arrays of index positions.
Can I combine fancy and boolean indexing?
Can I combine fancy and boolean indexing?
Yes, you can combine both indexing methods to perform advanced filtering and selection operations on NumPy arrays.
Does fancy indexing return a view or a copy?
Does fancy indexing return a view or a copy?
Fancy indexing returns a copy of the original data. This means that changes made to the result will not affect the original array.
What's Next?
Now that you’ve explored Fancy and Boolean Indexing, you’re ready to understand how data is stored and shared in NumPy arrays through views and copies.
Knowing the difference between a view and a copy is crucial to avoid unexpected bugs when working with large datasets or modifying arrays.