🎯 NumPy Advanced Indexing: The Magic Treasure Hunt!
Imagine you have a giant toy box filled with numbered toys. Sometimes you want to grab specific toys—not just “the third one” but “all the red ones” or “toys numbered 5, 10, and 15.” That’s what Advanced Indexing does in NumPy!
🌟 The Story: The Magical Treasure Chest
Once upon a time, there was a magical treasure chest (your NumPy array). Inside were precious gems (numbers). The chest was smart—you could ask it questions, and it would hand you exactly the gems you wanted!
import numpy as np
# Our magical treasure chest
chest = np.array([10, 20, 30, 40, 50])
🔍 Boolean Indexing: Ask Yes/No Questions!
What Is It?
Think of it like asking your toy box: “Which toys are bigger than 25?”
The box answers with True or False for each toy. Then it hands you only the “True” toys!
Simple Example
chest = np.array([10, 20, 30, 40, 50])
# Ask: "Which gems are bigger than 25?"
answer = chest > 25
print(answer)
# [False False True True True]
# Grab only the True ones!
big_gems = chest[chest > 25]
print(big_gems)
# [30 40 50]
Real Life
- Finding all students who scored above 70
- Getting all temperatures above freezing
- Selecting all products under $50
🎠Creating Boolean Masks: Your Magic Filter!
What Is It?
A Boolean Mask is like a magic stencil. You lay it over your array, and only the parts marked “True” show through!
Building Your Mask
scores = np.array([85, 42, 91, 67, 55])
# Create the mask: "Who passed?" (score >= 60)
passed_mask = scores >= 60
print(passed_mask)
# [ True False True True False]
# Use the mask to grab passing scores
passing = scores[passed_mask]
print(passing)
# [85 91 67]
Combining Masks (Multiple Questions!)
You can ask two questions at once using:
&means “AND” (both must be True)|means “OR” (either can be True)
ages = np.array([12, 25, 8, 30, 15])
# Who is a teenager? (13-19)
teen_mask = (ages >= 13) & (ages <= 19)
print(ages[teen_mask])
# [15]
# Who is a child OR adult? (not teen)
other_mask = (ages < 13) | (ages > 19)
print(ages[other_mask])
# [12 25 8 30]
Important: Always use parentheses around each condition!
🎪 Fancy Indexing: Pick by Number List!
What Is It?
Imagine telling your toy box: “Give me toys #2, #4, and #0!”
Instead of picking one toy at a time, you hand it a shopping list of positions!
Simple Example
fruits = np.array(['apple','banana','cherry',
'date','elderberry'])
# My shopping list: positions 0, 2, 4
picks = [0, 2, 4]
basket = fruits[picks]
print(basket)
# ['apple' 'cherry' 'elderberry']
Using Another Array as Index
prices = np.array([100, 200, 150, 300, 250])
# Get prices at positions 3, 1, 4
wanted = np.array([3, 1, 4])
print(prices[wanted])
# [300 200 250]
Repeat Picking (Yes, You Can!)
nums = np.array([10, 20, 30])
# Pick position 0 three times!
repeated = nums[[0, 0, 0, 1, 2]]
print(repeated)
# [10 10 10 20 30]
đź”® np.where: The Smart Chooser!
What Is It?
np.where is like a smart helper that:
- Looks at each item
- Asks “Does this pass the test?”
- If yes → picks one value
- If no → picks another value
Finding Positions
temps = np.array([35, 28, 42, 31, 39])
# Where is it hot? (above 35)
hot_spots = np.where(temps > 35)
print(hot_spots)
# (array([2, 4]),) # positions 2 and 4
The Magic Three-Part Trick!
np.where(condition, yes_value, no_value)
grades = np.array([85, 42, 91, 58, 73])
# Label each: "Pass" or "Fail"
result = np.where(grades >= 60,
'Pass',
'Fail')
print(result)
# ['Pass' 'Fail' 'Pass' 'Fail' 'Pass']
Replace Values Conditionally
data = np.array([5, -3, 8, -1, 2])
# Replace negatives with 0
clean = np.where(data < 0, 0, data)
print(clean)
# [5 0 8 0 2]
🗺️ Visual Summary
graph TD A[Your Array] --> B{What do you need?} B -->|Yes/No filter| C[Boolean Indexing] B -->|Specific positions| D[Fancy Indexing] B -->|Conditional replace| E[np.where] C --> F[arr bigger than 5] D --> G[arr with list 0 2 4] E --> H[np.where cond x y]
🎯 Quick Reference
| Method | When to Use | Example |
|---|---|---|
| Boolean | Filter by condition | arr[arr > 5] |
| Mask | Reusable filter | mask = arr > 5 |
| Fancy | Pick specific spots | arr[[1,3,5]] |
| np.where | Find or replace | np.where(arr>0) |
đź’ˇ Remember This!
- Boolean = Asking questions → Get True/False answers
- Mask = Save the answer → Reuse it later
- Fancy = Shopping list → Pick exact positions
- np.where = Smart swap → Replace based on rules
🚀 You Did It!
Now you’re a treasure hunting expert! You can:
- âś… Ask questions about your data (Boolean)
- âś… Create reusable filters (Masks)
- âś… Pick items by position list (Fancy)
- âś… Smartly replace values (np.where)
Go forth and index like a pro! 🎉