Fancy Indexing

Summary: in this tutorial, you’ll learn about the fancy indexing technique to select elements of a numpy array.

Introduction to fancy indexing

In the previous tutorial, you learned how to select elements from a numpy array using indexing and slicing techniques.

Besides using indexing & slicing, NumPy provides you with a convenient way to index an array called fancy indexing.

Fancy indexing allows you to index a numpy array using the following:

Let’s see the following example:

import numpy as np

a = np.arange(1, 10)
print(a)

indices = np.array([2, 3, 4])
print(a[indices])Code language: PHP (php)

Output:

[1 2 3 4 5 6 7 8 9]
[3 4 5]Code language: JSON / JSON with Comments (json)

How it works.

Numpy Fancy Indexing

First, use the arange() function to create a numpy array that includes numbers from 1 to 9:

[1 2 3 4 5 6 7 8 9]Code language: JSON / JSON with Comments (json)

Second, create a second numpy array for indexing:

indices = np.array([2, 3, 4])Code language: PHP (php)

Third, use the indices array for indexing the a array:

print(a[indices])Code language: CSS (css)

Summary

  • Fancy indexing allows you to index an array using another array, a list, or a sequence of integers.
Did you find this tutorial helpful ?