Numpy Python

πŸ“˜ Chapter 4: Indexing and Slicing in NumPy β€” Unlocking the Secrets of Array Access

🧠 β€œ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

arr2d = np.array([[1, 2, 3],
                  [4, 5, 6],
                  [7, 8, 9]])

print("Element at row 1, column 2:", arr2d[1, 2])  # Output: 6

You can also use chained syntax:

print(arr2d[1][2])

 

🧱 Three-Dimensional Arrays

arr3d = np.array([
    [[1, 2], [3, 4]],
    [[5, 6], [7, 8]]
])

print("Element:", arr3d[1, 0, 1])  # Output: 6

🧠 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

arr[1:3] = [55, 66]
print(arr)  # Output: [1 55 66 4]

πŸ”Ί Changing 2D Blocks

arr2d = np.array([[1, 2, 3],
                  [4, 5, 6]])

arr2d[0, 1:] = [77, 88]
print(arr2d)

 

Output:

[[ 1 77 88]
 [ 4  5  6]]

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

arr = np.array([10, 20, 30, 40, 50])
indices = [1, 3, 4]
print(arr[indices])  # Output: [20 40 50]

πŸ”Ή Example 2: Rows and Columns by Index

arr2d = np.array([[10, 20],
                  [30, 40],
                  [50, 60]])

print(arr2d[[0, 2], [1, 0]])  # Output: [20 50]

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

arr2d = np.array([
    [10, 15],
    [25, 30]
])

print(arr2d[arr2d >= 20])  # Output: [25 30]

Boolean indexing is a game-changer in:

  • Data cleaning

  • Outlier removal

  • Condition-based subsetting

  • Model training filtering


πŸ’‘ Bonus: Combining Indexing Tricks

arr = np.arange(1, 21).reshape(4, 5)
print("Original:\n", arr)

# Access middle 2x2 block
print("Middle Block:\n", arr[1:3, 1:3])

# Set top row to 99
arr[0, :] = 99
print("Modified:\n", arr)

# Extract all even numbers
print("Evens:\n", arr[arr % 2 == 0])

 


🧠 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!

Leave a Reply

Your email address will not be published. Required fields are marked *