NumPy Lesson 26 – Advanced Indexing | Dataplexa

Advanced Indexing in NumPy

NumPy provides powerful indexing techniques that go far beyond simple integer indexing and slicing. These advanced methods allow you to select and manipulate data efficiently using arrays and conditions.

In this lesson, you will learn how advanced indexing works and when to use it in real-world data processing.


What Is Advanced Indexing?

Advanced indexing occurs when you use:

  • Arrays of indices
  • Boolean masks
  • Multiple index arrays together

Unlike slicing, advanced indexing always returns a copy of the data.


Indexing with Integer Arrays

You can select specific elements by providing an array of indices.

import numpy as np

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

indices = [0, 2, 4]
result = arr[indices]

print(result)

Output:

[10 30 50]

Only the elements at the specified positions are selected.


Advanced Indexing in 2D Arrays

You can also use arrays of row and column indices.

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

rows = [0, 1, 2]
cols = [2, 1, 0]

print(matrix[rows, cols])

Output:

[3 5 7]

Each pair of indices selects one element.


Boolean Indexing

Boolean indexing selects elements based on conditions.

numbers = np.array([5, 10, 15, 20, 25])

filtered = numbers[numbers > 15]
print(filtered)

Output:

[20 25]

Only values that satisfy the condition are returned.


Multiple Conditions

Use logical operators to combine conditions.

data = np.array([12, 18, 25, 30, 45])

result = data[(data > 15) & (data < 40)]
print(result)

Output:

[18 25 30]

Parentheses are required when combining conditions.


Setting Values Using Advanced Indexing

Advanced indexing can also modify array values.

scores = np.array([45, 60, 75, 30])

scores[scores < 50] = 50
print(scores)

Output:

[50 60 75 50]

This is commonly used for data cleaning.


Difference Between Slicing and Advanced Indexing

  • Slicing returns a view when possible
  • Advanced indexing always returns a copy
  • Advanced indexing is more flexible but slightly slower

When to Use Advanced Indexing

  • Filtering datasets
  • Selecting non-contiguous elements
  • Conditional data modification
  • Working with real-world datasets

Practice Exercise

Task

  • Create a NumPy array of numbers from 1 to 20
  • Select only even numbers
  • Replace values greater than 15 with 15

What’s Next?

In the next lesson, you will learn about Meshgrid and how NumPy generates coordinate matrices for numerical computations.