In NumPy, fancy indexing allows us to use an array of indices to access multiple array elements at once.
Fancy indexing can perform more advanced and efficient array operations, including conditional filtering, sorting, and so on.
Select Multiple Elements Using NumPy Fancy Indexing
In this example, the resulting array select_elements contains the elements of array1 that correspond to the indices [1, 2, 5, 7] which are 2, 3, 6, and 8 respectively.
Example: NumPy Fancy Indexing
Output
Simple Indexing: 4 Fancy Indexing: [2 3 6 8]
Note: To learn more about simple NumPy array indexing, visit NumPy Array Indexing.
Fancy Indexing for Sorting NumPy Array
Fancy indexing can also sort a NumPy array. Let's see an example.
Here, we are using the fancy indexing with the argsort() function to sort the array1 in the ascending order.
We could also use fancy indexing to sort the array in descending order.
Here, first we multiplied array1 by -1 to sort in descending order and then used the fancy indexing to return the sorted array.
Fancy Indexing to Assign New Values to Specific Elements
We can also assign new values to specific elements of a NumPy array using fancy indexing. For example,
In this example, first we have created a list of indices called indices which specifies the elements of array1 that we want to assign new values to.
Then we created the array for new values called new_values that we want to assign to the specified indices.
Finally, we used fancy indexing with the list of indices to assign the new values to the specified elements of array1.
Fancy Indexing on N-d Arrays
We can also use fancy indexing on multi-dimensional arrays.
Let's see an example to select specific rows using fancy indexing.
Output
[[ 1 3 5] [13 18 29]]
Here, we have created a 2D array named array1 and an array of row indices named row_indices.
Then, we used fancy indexing to select the rows with indices 0 and 2 from array1.
Note: To learn more about N-d array indexing, visit NumPy Array Indexing.