0
0
NumPydata~5 mins

Fancy indexing with integer arrays in NumPy

Choose your learning style9 modes available
Introduction

Fancy indexing lets you pick specific items from data using lists of positions. It helps you get or change many values at once easily.

You want to select multiple specific rows from a table by their row numbers.
You need to update certain elements in a list or array based on their positions.
You want to reorder data by giving a new order of indexes.
You want to extract scattered values from a big dataset quickly.
Syntax
NumPy
import numpy as np

# Create an array
array = np.array([10, 20, 30, 40, 50])

# Use a list or array of integers to pick elements
indexes = [1, 3, 4]
selected_elements = array[indexes]

The indexes can be a Python list or a NumPy array of integers.

Fancy indexing returns a new array with the selected elements.

Examples
Selects elements at positions 0, 2, and 4 from the array.
NumPy
import numpy as np

array = np.array([5, 10, 15, 20, 25])
indexes = [0, 2, 4]
print(array[indexes])
Empty index list returns an empty array (edge case: no elements selected).
NumPy
import numpy as np

array = np.array([5, 10, 15, 20, 25])
indexes = []
print(array[indexes])
Single element array and selecting that one element.
NumPy
import numpy as np

array = np.array([5])
indexes = [0]
print(array[indexes])
Selects elements at the end and beginning, showing order can be changed.
NumPy
import numpy as np

array = np.array([5, 10, 15, 20, 25])
indexes = [4, 0]
print(array[indexes])
Sample Program

This program shows how to pick elements from an array using a list of indexes, then change those elements in the original array.

NumPy
import numpy as np

# Create an array of numbers
numbers = np.array([100, 200, 300, 400, 500])
print("Original array:", numbers)

# Choose indexes to select
selected_indexes = [1, 3, 4]

# Use fancy indexing to get elements at these positions
selected_numbers = numbers[selected_indexes]
print("Selected elements at positions 1, 3, 4:", selected_numbers)

# Change elements at these positions
numbers[selected_indexes] = [210, 410, 510]
print("Array after updating selected positions:", numbers)
OutputSuccess
Important Notes

Time complexity is O(k) where k is the number of indexes selected.

Space complexity is O(k) for the new array created by fancy indexing.

A common mistake is using indexes out of range, which causes an error.

Use fancy indexing when you want to select or update multiple specific elements at once. For continuous slices, normal slicing is simpler and faster.

Summary

Fancy indexing lets you pick or change many elements by giving their positions in a list.

It works with lists or arrays of integers as indexes.

It creates a new array of selected elements or updates the original array if assigned.