π§ βThink of a NumPy array like a treasure chest. Indexing is your map, slicing is your sword.β
Welcome back, array adventurer! π§ββοΈ
Weβve journeyed through creating arrays, understanding their structure, and decoding their dimensions. Now itβs time to access, modify, and manipulate those arrays like a pro.
In Python, slicing and indexing are second nature when working with lists. But with NumPy, the magic goes deeper β enabling you to access entire rows, columns, subarrays, and even non-contiguous data in milliseconds.
This chapter covers:
-
Accessing elements and subarrays
-
Modifying array values
-
Fancy indexing tricks
-
Boolean slicing (the coolest one!)
Letβs decode the art of slicing arrays like a ninja π₯·
π’ 1. Accessing Elements: Indexing Basics
π§© One-Dimensional Arrays
import numpy as np arr = np.array([10, 20, 30, 40, 50]) print("First element:", arr[0]) print("Last element:", arr[-1])
Just like Python lists, NumPy uses zero-based indexing.
π§ Two-Dimensional Arrays
You can also use chained syntax:
print(arr2d[1][2])
π§± Three-Dimensional Arrays
π§ Think of it like this:
-
First index: depth (which βblockβ)
-
Second index: row
-
Third index: column
π‘ 2. Accessing Subarrays: Slicing
πΉ Syntax Recap: array[start:stop:step]
π§© 1D Slicing
arr = np.array([10, 20, 30, 40, 50]) print("From index 1 to 3:", arr[1:4]) # Output: [20 30 40] print("Every other element:", arr[::2]) # Output: [10 30 50]
π§ 2D Slicing
arr2d = np.array([ [11, 12, 13], [21, 22, 23], [31, 32, 33] ]) print("First two rows:\n", arr2d[:2]) print("Last column:\n", arr2d[:, 2]) # All rows, column index 2 print("Middle block:\n", arr2d[1:, 1:])
π Tip: Use :
to mean βallβ β it’s your wildcard!
π΄ 3. Modifying Array Values
Arrays in NumPy are mutable β meaning you can change their content in place.
πΈ Changing Single Elements
arr = np.array([1, 2, 3, 4]) arr[2] = 99 print(arr) # Output: [1 2 99 4]
πΉ Changing Slices
πΊ Changing 2D Blocks
Output:
Be mindful: slicing returns a view, not a copy!
Changes to the slice will affect the original array.
π‘ 4. Fancy Indexing β Level Up!
Fancy indexing lets you access multiple arbitrary elements β not just a range.
πΉ Example 1: Selecting specific elements
πΉ Example 2: Rows and Columns by Index
Hereβs what happened:
-
First row, second column β 20
-
Third row, first column β 50
π£ 5. Boolean Indexing β The Magic Filter πͺ
This is where NumPy gets really powerful. You can filter arrays based on conditions.
Example: Filter values > 25
arr = np.array([10, 25, 30, 5, 40]) condition = arr > 25 print("Condition:", condition) print("Filtered values:", arr[condition])
Output:
[False False True False True] [30 40]
Or directly:
print(arr[arr > 25]) # Output: [30 40]
Use with 2D arrays
Boolean indexing is a game-changer in:
-
Data cleaning
-
Outlier removal
-
Condition-based subsetting
-
Model training filtering
π‘ Bonus: Combining Indexing Tricks
π§ Real-World Use Cases
Task | How Indexing Helps |
---|---|
Select data by condition | data[data > threshold] |
Replace outliers | data[data > 100] = 100 |
Extract rows by index | data[[0, 3, 7]] |
Extract columns | data[:, 2] |
Select region in image | image[100:200, 100:200] |
β οΈ Common Mistakes to Avoid
Mistake | Correction |
---|---|
Mixing up rows/columns | Remember: array[row, column] |
Forgetting slicing is a view | Use .copy() if needed |
Indexing with floats | Only use integers or booleans |
Wrong dimensions | Check ndim before slicing deeply |
π Summary Table: Indexing & Slicing
Concept | Example | Result |
---|---|---|
Index 1D | arr[2] |
Single element |
Index 2D | arr[1, 2] |
Element at row 1, col 2 |
Slice 1D | arr[1:4] |
Subarray |
Slice 2D | arr[:2, 1:] |
Rows 0-1, cols 1-end |
Fancy | arr[[1, 3]] |
Indexed elements |
Boolean | arr[arr > 10] |
Elements > 10 |
π Wrapping Up Chapter 4
By now, youβve unlocked the ability to:
-
Navigate arrays with precision
-
Extract and modify values
-
Use conditions to filter data with ease
This chapter was all about data access β an essential step in analysis, transformation, and preprocessing. Once you master this, everything from image data to financial modeling becomes manageable.
π Next Up in Chapter 5:
Weβll dive into Mathematical and Statistical Operations in NumPy, covering:
-
Aggregates like sum, mean, min, max
-
Axis-based operations
-
Element-wise math functions
-
And more broadcasting magic!