We use np.argsort() to find the order of elements that would sort an array. It tells us the positions to rearrange the data instead of sorting the data itself.
np.argsort() for sort indices in NumPy
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
NumPy
np.argsort(a, axis=-1, kind='quicksort', order=None)
a is the input array to find sort indices for.
The result is an array of indices that sort a.
Examples
[3, 1, 2]. The output shows positions of elements in ascending order.NumPy
import numpy as np arr = np.array([3, 1, 2]) indices = np.argsort(arr) print(indices)
NumPy
arr = np.array([[3, 1], [2, 4]]) indices = np.argsort(arr, axis=1) print(indices)
argsort to sort the array by rearranging elements using the indices.NumPy
arr = np.array([3, 1, 2]) sorted_arr = arr[np.argsort(arr)] print(sorted_arr)
Sample Program
This program shows how to get sort indices with np.argsort(), use them to sort the array, and find the rank (position) of each element in the sorted order.
NumPy
import numpy as np # Original array arr = np.array([50, 20, 30, 10, 40]) # Get indices that would sort the array sort_indices = np.argsort(arr) print('Sort indices:', sort_indices) # Use indices to sort the array sorted_arr = arr[sort_indices] print('Sorted array:', sorted_arr) # Example: Find rank of each element ranks = np.empty_like(sort_indices) ranks[sort_indices] = np.arange(len(arr)) print('Ranks of elements:', ranks)
Important Notes
np.argsort() returns indices, not sorted values.
You can use the indices to reorder the original array or related arrays.
For multidimensional arrays, specify axis to sort along rows or columns.
Summary
np.argsort() gives the order of indices to sort an array.
Use it to sort arrays without changing the original data directly.
It helps find rankings and reorder related data consistently.
Practice
1. What does the
np.argsort() function return when applied to a numpy array?easy
Solution
Step 1: Understand the purpose of
This function does not sort the array directly but returns the indices that would sort the array.np.argsort()Step 2: Differentiate from sorting functions
Unlikenp.sort()which returns the sorted array,np.argsort()returns the order of indices to achieve that sorting.Final Answer:
An array of indices that would sort the original array -> Option DQuick Check:
np.argsort()= indices order [OK]
Hint: Remember: argsort returns indices, not sorted values [OK]
Common Mistakes:
- Confusing argsort with sort and expecting sorted values
- Thinking argsort returns the maximum or minimum value
- Assuming argsort returns a scalar instead of an array
2. Which of the following is the correct syntax to get the indices that would sort the array
arr using a NumPy function?easy
Solution
Step 1: Identify the numpy function for argsort
The functionnp.argsort()is called with the array as argument:np.argsort(arr).Step 2: Differentiate from other methods
arr.argsort()is an array method (not the NumPy function), whilenp.sort(arr)returns sorted values, andarr.sort()sorts in place.Final Answer:
np.argsort(arr) -> Option BQuick Check:
Correct function call = np.argsort(arr) [OK]
Hint: Use np.argsort(array), the NumPy function, to get sort indices [OK]
Common Mistakes:
- Using arr.argsort() (array method instead of NumPy function)
- Confusing np.sort() with np.argsort()
- Using arr.sort() which sorts in place and returns None
3. Given the code:
What will be the output?
import numpy as np arr = np.array([40, 10, 30, 20]) indices = np.argsort(arr) print(indices)
What will be the output?
medium
Solution
Step 1: Understand the array and sorting order
The array is [40, 10, 30, 20]. Sorting it ascending gives [10, 20, 30, 40].Step 2: Find indices that sort the array
10 is at index 1, 20 at index 3, 30 at index 2, and 40 at index 0. So, indices are [1, 3, 2, 0].Final Answer:
[1 3 2 0] -> Option AQuick Check:
Sorted indices = [1 3 2 0] [OK]
Hint: Match sorted values to original indices for argsort output [OK]
Common Mistakes:
- Confusing sorted values with indices
- Reversing the order of indices
- Using sorted array instead of indices
4. What is wrong with this code snippet?
import numpy as np arr = np.array([3, 1, 2]) indices = arr.argsort() print(indices)
medium
Solution
Step 1: Check if
In numpy, arrays do have anargsort()is a valid numpy array methodargsort()method, soarr.argsort()is valid.Step 2: Verify code correctness
The code will run and print the indices that sort the array, which are [1, 2, 0].Final Answer:
The code will run correctly and print the sorted indices -> Option AQuick Check:
arr.argsort() is valid and works [OK]
Hint: Remember numpy arrays have argsort() method too [OK]
Common Mistakes:
- Assuming argsort() is only in np module, not array method
- Thinking array must be sorted before argsort()
- Confusing Python 2 print syntax with Python 3
5. You have two related numpy arrays:
You want to list the fruit names sorted by their prices in ascending order. Which code snippet correctly achieves this?
names = np.array(['apple', 'banana', 'cherry', 'date']) prices = np.array([3.5, 2.0, 4.0, 1.5])
You want to list the fruit names sorted by their prices in ascending order. Which code snippet correctly achieves this?
hard
Solution
Step 1: Use
This returns indices that sort prices ascending.np.argsort(prices)to get indices that sort pricesStep 2: Use these indices to reorder
Indexingnamesnameswith these indices sorts names by price.Final Answer:
sorted_names = names[np.argsort(prices)] -> Option CQuick Check:
Index names by argsort(prices) to sort by price [OK]
Hint: Index names by argsort of prices to sort related arrays [OK]
Common Mistakes:
- Trying to sort names directly without using indices
- Using np.sort(names) which sorts names alphabetically
- Indexing with sorted prices instead of indices
