How to Sort Array in NumPy: Simple Syntax and Examples
To sort an array in NumPy, use
np.sort(array) to return a sorted copy or array.sort() to sort the array in place. Both methods sort elements in ascending order by default.Syntax
NumPy provides two main ways to sort arrays:
np.sort(array, axis=-1, kind='quicksort', order=None): Returns a sorted copy of the array.array.sort(axis=-1, kind='quicksort', order=None): Sorts the array in place, modifying the original array.
Parameters:
array: The NumPy array to sort.axis: The axis along which to sort. Default is the last axis.kind: Sorting algorithm ('quicksort', 'mergesort', 'heapsort', 'stable').order: When sorting structured arrays, specifies field names.
python
import numpy as np # Using np.sort returns a sorted copy sorted_array = np.sort(np.array([3, 1, 2])) # Using ndarray.sort sorts in place arr = np.array([3, 1, 2]) arr.sort()
Example
This example shows how to sort a 1D and 2D NumPy array using both np.sort and array.sort(). It also demonstrates sorting along different axes.
python
import numpy as np # 1D array arr1d = np.array([5, 2, 9, 1]) sorted_copy = np.sort(arr1d) # Original array remains unchanged # Sort in place arr1d.sort() # 2D array arr2d = np.array([[3, 7, 5], [8, 4, 6]]) # Sort each row (axis=1) sorted_rows = np.sort(arr2d, axis=1) # Sort each column (axis=0) sorted_cols = np.sort(arr2d, axis=0) sorted_copy, arr1d, sorted_rows, sorted_cols
Output
(
array([1, 2, 5, 9]),
array([1, 2, 5, 9]),
array([[3, 5, 7],
[4, 6, 8]]),
array([[3, 4, 5],
[8, 7, 6]])
)
Common Pitfalls
1. Confusing np.sort() and array.sort(): np.sort() returns a new sorted array, leaving the original unchanged, while array.sort() changes the original array.
2. Forgetting to assign the result of np.sort(): Since it returns a new array, you must save it to a variable.
3. Sorting multi-dimensional arrays without specifying axis: By default, sorting happens along the last axis, which may not be what you expect.
python
import numpy as np arr = np.array([3, 1, 2]) # Wrong: does not change arr np.sort(arr) print(arr) # Output: [3 1 2] # Right: assign sorted array arr_sorted = np.sort(arr) print(arr_sorted) # Output: [1 2 3] # Sort in place arr.sort() print(arr) # Output: [1 2 3]
Output
[3 1 2]
[1 2 3]
[1 2 3]
Quick Reference
Here is a quick summary of sorting arrays in NumPy:
| Function/Method | Description | Modifies Original Array? |
|---|---|---|
| np.sort(array, axis=-1) | Returns a sorted copy of the array | No |
| array.sort(axis=-1) | Sorts the array in place | Yes |
Key Takeaways
Use np.sort(array) to get a sorted copy without changing the original array.
Use array.sort() to sort the array in place and modify the original data.
Specify the axis parameter to control sorting direction in multi-dimensional arrays.
Remember to assign the result of np.sort() if you want to keep the sorted array.
Choose the sorting algorithm with the kind parameter if needed, default is quicksort.