
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
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)]