Fancy indexing is a method used when working in arrays. It is an advanced form of simple indexing. An index is used to represent the position of an element within a given array. Fancy indexing is used to get multiple elements by passing a list of indices. For example, given a list of numbers, the position of any of the elements in the list can easily be found by passing an index as shown below:
#import numpy libraryimport numpy as np#creating an array, XX = np.array([1, 12, 31, 4, 50, 6, 7, 28, 9, 20])#returning the number in the fifth positionprint(X[4]) #python index begins from zero
The code above demonstrates simple indexing in NumPy:
Line 2: We import the NumPy library as np
.
Line 5: We pass a list of numbers into the np.array()
function and assign it to the variable, X
. This creates a NumPy array.
Line 8: We use the print()
method to pass the index [4]
, into the previously created array, X
. Then we print the results. This returns the number at the fifth position, 50
.
In the code above, we pass the index, 4
, to return the number in the fifth position, 50
. We can use a list of indices to return the numbers in the first, fourth, fifth, and eighth position. We do so by using the list, X
, and a list of indices, y
.
#import numpy libraryimport numpy as np#creating an array, XX = np.array([1, 12, 31, 4, 50, 6, 7, 28, 9, 20])#list of indices, Yy = [0,3,4,7]#fancy indexingprint(X[y])
The code above demonstrates fancy indexing in NumPy:
Line 2: We import the NumPy library as np
.
Line 5: We pass a list of numbers into the np.array()
function and assign it to the variable, X
. This creates a NumPy array.
Line 8: We assign a list of indices corresponding to the first, fourth, fifth, and eighth position to the variable, y
.
Line 11: We use the print()
method to pass y
as an index into X
and print it. Then, we print the list of numbers corresponding to the index positions in y
to the console.
Fancy indexing enables the selection of multiple elements at once. It also eliminates the problem of repetition when returning multiple elements from an array by index.
Free Resources