Chapter 6: NumPy Array Indexing

NumPy Array Indexing written as if a patient teacher is sitting next to you, showing examples on the screen, explaining the logic, warning about common traps, and showing realistic patterns you will actually use.

Let’s go slowly and thoroughly — indexing is one of the most important skills in NumPy.

Python

1. Basic Indexing – Like lists, but more powerful

Python

2D array example

Python

Important rule to remember early:

text

2. Slicing – The most frequently used operation

Slicing syntax: start:stop:step

All three parts are optional.

Python

2D slicing examples (very common)

Python

3. Boolean Indexing – Extremely powerful (you will use this daily)

Instead of numbers, you give a boolean mask of the same shape.

Python

Realistic example – cleaning data

Python

Replacing values conditionally (very frequent pattern)

Python

4. Fancy Indexing – Using arrays/lists of indices

You can pass an array or list of indices → picks elements in that order.

Python

2D fancy indexing – very common pattern

Python

5. Combining styles – Very powerful & common

Python

6. Views vs Copies – The trap almost everyone falls into

Most indexing creates a view (not a copy) → changes affect original array!

Python

How to force a copy:

Python

Quick rule of thumb (very useful):

Operation Usually returns
Basic slicing a[2:5] View
Boolean indexing a[a>0] Copy
Fancy indexing a[[1,3,5]] Copy
a[…] with lists/arrays Copy
.copy() Copy

7. Realistic patterns you will write again and again

Pattern 1: Normalize only selected columns

Python

Pattern 2: Remove rows with outliers

Python

Pattern 3: Get top-k scores

Python

Summary Table – Quick Reference

You want… Syntax example
Single element arr[3], mat[2,1]
Row / column mat[1], mat[:,3]
Slice arr[2:7], mat[1:4, 2:]
Every nth element arr[::3], arr[::-1] (reverse)
Boolean filter arr[arr > 50], arr[arr % 2 == 0]
Replace conditionally arr[arr < 0] = 0
Fancy indexing (pick specific indices) arr[[1,4,7]], mat[[0,2], [1,3]]
Get copy (not view) arr[slice].copy()

Where would you like to go next?

  • Advanced indexing tricks (np.ix_, masking in multiple dimensions)
  • Differences between view vs copy in depth (with memory examples)
  • Indexing in 3D arrays / images
  • Boolean indexing + assignment patterns
  • Common bugs people make with indexing
  • Mini-project using indexing (data filtering & cleaning)

Just tell me what feels most useful right now! 😊

You may also like...

Leave a Reply

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