Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

NumPy - Sorting with Fancy Indexing



Sorting with Fancy Indexing in NumPy

Sorting with fancy indexing in NumPy involves using an array of indices to rearrange elements in another array. Fancy indexing allows you to sort or reorder an array based on specific indices, giving you more control over how you want the data to be organized.

For example, you can first determine the order of elements with argsort() function and then use these indices to sort the original array. This is useful for complex data manipulation tasks where you need precise control over the order of elements.

Basic Fancy Indexing

Basic fancy indexing involves using one or more arrays of indices to select elements from a NumPy array. These indices can be arrays of integers or boolean values, allowing for non-contiguous selection of elements. This is especially useful for reordering or selecting multiple elements simultaneously.

Example

In the following example, we are using fancy indexing to reorder an array based on a specified set of indices. By indexing "arr" with the "indices" array, we obtain a new array where the elements are arranged according to the given order −

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
indices = np.array([4, 2, 3, 1, 0])
sorted_arr = arr[indices]

print("Original Array:", arr)
print("Sorted Array with Fancy Indexing:", sorted_arr)

Following is the output obtained −

Original Array: [10 20 30 40 50]
Sorted Array with Fancy Indexing: [50 30 40 20 10]

Sorting Arrays Using Fancy Indexing

Sorting arrays with fancy indexing involves first creating an array of indices that represent the desired order of elements. These indices are then used to reorder the array elements according to specific criteria.

Fancy indexing provides a way to perform advanced sorting operations that go beyond simple in-place sorting.

Example

In this example, we are using np.argsort() function to retrieve the indices that would sort the array "arr". These indices are then used to rearrange "arr" into a sorted array −

import numpy as np

arr = np.array([3, 1, 4, 1, 5, 9])
# Get indices that would sort the array
sort_order = np.argsort(arr)  
sorted_arr = arr[sort_order]

print("Original Array:", arr)
print("Sorted Array:", sorted_arr)

This will produce the following result −

Original Array: [3 1 4 1 5 9]
Sorted Array: [1 1 3 4 5 9]

Fancy Indexing with Multi-dimensional Arrays

In multi-dimensional arrays, fancy indexing can be applied to reorder or select elements along specific axes.

By using arrays of indices, you can achieve various operations, such as sorting elements, rearranging rows or columns, and extracting specific data points.

Example: Fancy Indexing in 2D Arrays

In the example below, we are reordering the rows and columns of a 2D array using fancy indexing. By specifying "row_indices" and "col_indices", we rearrange the arrays rows and columns to produce a new reordered array −

import numpy as np

arr = np.array([[10, 20, 30], [40, 50, 60]])
row_indices = np.array([1, 0])
col_indices = np.array([2, 1, 0])

# Reorder rows and columns
reordered_arr = arr[row_indices][:, col_indices]

print("Original Array:\n", arr)
print("Reordered Array:\n", reordered_arr)

Following is the output of the above code −

Original Array:
[[10 20 30]
 [40 50 60]]
Reordered Array:
 [[60 50 40]
 [30 20 10]]

Example: Fancy Indexing in 3D Arrays

In a 3D array, fancy indexing can be used to reorder slices along the first axis. Here, by specifying "slice_indices", we rearrange the arrays slices to produce a new array with reordered slices −

import numpy as np

# Define a 3D NumPy array with shape (3, 2, 2)
arr = np.array([[[1, 2], [3, 4]], 
                [[5, 6], [7, 8]], 
                [[9, 10], [11, 12]]])

# Define an array of indices to reorder slices along the first axis
slice_indices = np.array([2, 0, 1])

# Reorder the slices using fancy indexing
reordered_slices = arr[slice_indices]

print("Original Array:\n", arr)
print("Reordered Slices:\n", reordered_slices)

The output obtained is as shown below −

Original Array:
[[[ 1  2]
  [ 3  4]]

 [[ 5  6]
  [ 7  8]]

 [[ 9 10]
  [11 12]]]
Reordered Slices:
[[[ 9 10]
  [11 12]]

 [[ 1  2]
  [ 3  4]]

 [[ 5  6]
  [ 7  8]]]

Sorting with Fancy Indexing and Structured Arrays

Fancy indexing can also be applied to structured arrays, where you sort based on the values of specific fields.

Structured arrays in NumPy are arrays with compound data types, where each element can have multiple fields with different data types. These are useful for managing heterogeneous data in a single array.

Example

In the following example, we are sorting a structured NumPy array based on the "age" field. By using np.argsort() function on the age field, we obtain the indices to reorder the array, resulting in a new array sorted by age −

import numpy as np

dtype = [('name', 'S10'), ('age', 'i4')]
values = [('Alice', 25), ('Bob', 30), ('Charlie', 20)]
arr = np.array(values, dtype=dtype)

# Sort by age
sorted_indices = np.argsort(arr['age'])
sorted_arr = arr[sorted_indices]

print("Original Structured Array:\n", arr)
print("Sorted by Age:\n", sorted_arr)

We get the output as shown below −

Original Structured Array:
[(b'Alice', 25) (b'Bob', 30) (b'Charlie', 20)]
Sorted by Age:
[(b'Charlie', 20) (b'Alice', 25) (b'Bob', 30)]
Advertisements