To sort the elements of the NumPy array in ordered sequence use numpy.sort()
function. By using this you can sort an N-dimensional array of any data type. In some cases, we require a sorted array for computation. This function gives a sorted copy of the source array or input array.
In this article, I will explain how to sort NumPy arrays with examples by using numpy.sort()
.
1. Quick Examples of NumPy Arrays sort()
If you are in a hurry, below are some quick examples of how to sort array elements in Python NumPy.
# Below are a quick examples
# Example 1: Sort in ascending order
array = np.array([5,8,6,12,3,15,1])
sorted_array = np.sort(array)
# Example 2: Use numpy.sort() to Sort a multi-dimensional array
arr = np.array([[12, 15, 7], [13, 5,11], [8, 6, 10],[45,54,70]])
arr2 = np.sort(arr)
# Example 3: sort along the last axis
arr2 = np.sort(arr, axis = -1)
# Example 4: Sort multi-dimensional array
# along a specified axis
arr = np.array([[12, 15, 7], [13, 5,11], [8, 6, 10],[45,54,70]])
arr2 = np.sort(arr, axis= None)
# Example 5: Use numpy.sort() to first axis
arr2 = np.sort(arr, axis= 0)
# Example 6: Sort the array alphabetically
arr = np.array([['orange','mango','grapes'], ['banana','cherry','apple'], ['papaya','watermelon','jackfruit']])
arr2 = np.sort(arr)
# Example 7: Sort a boolean array
arr = np.array([[True, False, True],[False, True, True],[False, False, True]])
arr2 = np.sort(arr)
# Example 8: Use numpy.ndarray.sort()
# to sort in descending order
array = np.array([5,8,6,12])
array[::-1].sort()
# Example 9: Use numpy.ndarray.sort()
array_copy = np.sort(array)[::-1]
2. NumPy Array sort() Syntax
Following is the syntax of the sort().
# Syntax of NumPy array sort()
numpy.sort(arr, axis= -1, kind=None, order=None)
2.1 Parameter of sort()
This function allows four Parameters.
arr
: Array to be sorted.axis
: This parameter defines the axis along which sorting is performed. If this parameter is None, the array will be flattened before sorting, and by default, this parameter is set to -1, which sorts the array along with the last axis.order
: This parameter specifies which fields to compare first.kind
: [‘quicksort’{default}, ‘mergesort’, ‘stable’, ‘heapsort’]Sorting algorithm.
2.2 Return Value of sort()
The sort() returns a sorted copy of the input array, which is having the same shape and same type as an input.
3. Usage of NumPy Array sort()
Use numpy.sort()
function to sort the elements of NumPy array in an ordered sequence. The parameter arr
is mandatory. If you execute this function on a one-dimensional array, it will return a one-dimensional sorted array containing elements in ascending order.
3.1 Get A Sorted NumPy Array(Ascending Order)
First, let’s create a NumPy array using np.array() function and apply the sort. By default, it does the ascending order.
# Import NumPy module
import numpy as np
# Create NumPy array
array = np.array([5,8,6,12,3,15,1])
# To get a sorted array(ascending order)
sorted_array = np.sort(array)
print(sorted_array)
# Output
# [ 1 3 5 6 8 12 15]
From the above code, it returned a sorted copy of the NumPy array, but the original NumPy remains unchanged.
3.2 Get A Sorted NumPy Array (Descending Order)
So far, we have seen that by default numpy.sort()
function sorts the NumPy array in ascending order. Let’s see how to sort NumPy arrays in descending order.
By Sorting a NumPy array in descending order sorts the elements from largest to smallest value. You can use the syntax array[::-1]
to reverse the array. For example, sorting [5,8,6,12] in descending order results in [12 8 6 5].
# Create NumPy array
array = np.array([5,8,6,12])
# Use numpy.ndarray.sort() to sort
# An array in descending order
array[::-1].sort()
print(array)
# Output
# [12 8 6 5]
Alternatively, if you use numpy.sort(array)[::-1]
, it will create a reverse sorted copy of the array.
# Use np.sort(array) to sort
# An array in descending order
array_copy = np.sort(array)[::-1]
print(array_copy)
# Output
# [12 8 6 5]
4. Sort Multi-Dimensional Array Using NumPy sort()
When you pass a multi-dimensional array as a parameter to numpy.sort()
, which will sort the array in an ascending order. Use axis=-1
not to flatterns the array.
# Create NumPy arrays
arr = np.array([[12, 15, 7], [13, 5,11], [8, 6, 10],[45,54,70]])
Print("array:\n",arr)
# Output: array:
# [[12 15 7]
# [13 5 11]
# [ 8 6 10]
# [45 54 70]]
# Use numpy.sort() to Sort a multi-dimensional array
arr2 = np.sort(arr)
print("Sorted array:\n",arr2)
# Output: Sorted array:
# [[ 7 12 15]
# [ 5 11 13]
# [ 6 8 10]
# [45 54 70]]
# Sort along the last axis
arr2 = np.sort(arr, axis = -1)
print ("Sorted array along axis=-1:\n",arr2)
# Output: Sorted array along axis=-1:
# [[ 7 12 15]
# [ 5 11 13]
# [ 6 8 10]
# [45 54 70]]
4.1 Sort Multi-Dimensional NumPy Arrays Along Specified Axis
If you pass a multi-dimensional array as a parameter of numpy.sort() along a specified axis with the value None
, it will be flattened the array before sorting. Let’s see the below example,
# Create NumPy arrays
arr = np.array([[12, 15, 7], [13, 5,11], [8, 6, 10],[45,54,70]])
# Sort multi-dimensional array along a specified axis
arr2 = np.sort(arr, axis= None)
print(" Sorted array:\n",arr2)
# OutPut : Sorted array:
# [ 5 6 7 8 10 11 12 13 15 45 54 70]
When you pass a multi-dimensional array as a parameter of sort() along a specified axis with the value 0
, which will sort the array in ascending order column-wise.
# Use numpy.sort() to first axis
arr2 = np.sort(arr, axis= 0)
print("Sorted array:\n",arr2)
# OutPut: Sorted array:
# [[ 8 5 7]
# [12 6 10]
# [13 15 11]
# [45 54 70]]
5. Sort Different Types of NumPy Arrays
Use this function to sort arrays of different data types like an array of strings, a boolean array, etc. When you sort an array with characters, it sorts in alphabetical order.
# Sort the array alphabetically
arr = np.array([['orange','mango','grapes'], ['banana','cherry','apple'], ['papaya','watermelon','jackfruit']])
arr2 = np.sort(arr)
print(" Sorted array:\n",arr2)
# Output: Sorted array:
# [['grapes' 'mango' 'orange']
# ['apple' 'banana' 'cherry']
# ['jackfruit' 'papaya' 'watermelon']]
Let’s see sorting an array with boolean values.
# Sort a boolean array
arr = np.array([[True, False, True],[False, True, True],[False, False, True]])
arr2 = np.sort(arr)
print(arr2)
# Output
# [[False True True]
# [False True True]
# [False False True]]
6. Conclusion
In this article, I have explained how to sort NumPy array/arrays using the numpy.sort()
function with examples. And also I have explained how to sort Multi-Dimensional array values along with a specified axis value.
Happy Learning!!
Related Articles
- How to get values from NumPy Array by Index?
- How to Slice NumPy Array?
- Python NumPy Array Reshape
- How to Get NumPy Array Shape?
- Get NumPy Array Length
- NumPy Array Addition
- How to get Diagonal of NumPy Array Using diag()
- How to Check NumPy Array Equal?
- How To Compute Average Of NumPy Array?