NumPy Sort Array

  • Post author:
  • Post category:NumPy / Python
  • Post last modified:November 22, 2023
  • Reading time:19 mins read

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, you 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 numpy.sort() function syntax, usage, and how to sort the elements of a NumPy array with examples.

1. Quick Examples of Arrays sort()

If you are in a hurry, below are some quick examples of how to sort array elements in Python NumPy.


# Quick examples of numpy arrays sort()

# Example 1: Use numpy.sort() function
# To get a sorted array in ascending order
arr = np.array([5,8,6,12,3,15,1])
sorted_array = np.sort(arr)

# Example 2: Use numpy.ndarray.sort() function
# sort an array in descending order
arr[::-1].sort()

# Example 3: Use numpy.sort() function
# To get a sorted array and reverse the order
sorted_array = np.sort(arr)[::-1]

# Example 4: 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 5: Sort along the last axis
arr = np.array([[12, 15, 7], [13, 5,11], [8, 6, 10],[45,54,70]]) 
arr2 = np.sort(arr, axis = -1)  
.
# Example 6: 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 7: Sort along the first axis (axis=0)
arr2 = np.sort(arr, axis=0)

# Example 8: Sort along the second axis (axis=1)
arr3 = np.sort(arr, axis=1)

# Example 9: Sort the array alphabetically
arr = np.array([['orange','mango','grapes'], ['banana','cherry','apple'], ['papaya','watermelon','jackfruit']]) 
arr2 = np.sort(arr) 

# Example 10: Sorted array with boolean values
arr_bool = np.array([True, False, True, True, False, True])
sorted_arr_bool = np.sort(arr_bool)

2. Syntax of sort()

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: This is the input array that you want to sort.
  • 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. If the array is structured (i.e., if it has fields defined), this argument specifies the field to use when sorting.
  • kind : Sorting algorithm. Default is 'quicksort'. Other options include 'mergesort' and 'heapsort'.

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()

The numpy.sort() function can be used to sort the elements of a NumPy array in an ordered sequence. The arr parameter is mandatory, and 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)

To get a sorted NumPy array in ascending order, you can use the numpy.sort() function. For example, np.sort(arr) returns a new array sorted_array with the elements of the original array arr sorted in ascending order. The original array remains unchanged.


# Import NumPy Module
import numpy as np

# Create numpy array
arr = np.array([5,8,6,12,3,15,1])
print("Original array:\n", arr)

# Use numpy.sort() function
# To get a sorted array in ascending order
sorted_array = np.sort(arr)
print("Sorted array in ascending order:\n",sorted_array)

Yields below output.

numpy array sort

3.2 Get a Sorted NumPy Array (Descending Order)

To get a sorted NumPy array in descending order, you can use the numpy.sort() function to obtain a sorted copy and then use slicing to reverse the order.

If you want to sort the array in descending order in-place (modify the original array), you can use the sort() method of the NumPy array with the order parameter set to descend. 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,3,15,1] in descending order results in [15 12 8 6 5 3 1].


# Create numpy array
arr = np.array([5,8,6,12,3,15,1])
print("Original array:\n", arr)

# Use numpy.ndarray.sort() function
# sort an array in descending order
arr[::-1].sort()
print("Sorted array in descending order (in-place):\n",arr)

Yields below output.

numpy array sort

Alternatively, np.sort(arr) returns a new array with the elements of the original array arr sorted in ascending order. Then, the [::-1] slicing is used to reverse the order, resulting in a sorted array in descending order.


# Use numpy.sort() function
# To get a sorted array and reverse the order
sorted_array = np.sort(arr)[::-1]
print("Sorted array in descending order:\n",sorted_array)

Yields the same output as above.

4. Sort Multi-Dimensional Array Using sort() Function

When you pass a multi-dimensional array as a parameter to numpy.sort(), it will sort the array in ascending order. You can sort a 2D NumPy array along the last axis (axis=-1). The np.sort(arr,axis=-1) sorts each row along the last axis independently, resulting in a new array arr2 where each row is sorted in ascending order. Use axis=-1 not to flatten the array.


# Create NumPy arrays   
arr = np.array([[12, 15, 7], [13, 5,11], [8, 6, 10],[45,54,70]]) 
print("Original array:\n", arr)

# Use numpy.sort() to Sort a multi-dimensional array
arr2 = np.sort(arr) 
print("Sorted multi-dimensional array:\n",arr2)
 
# Sort along the last axis
arr2 = np.sort(arr, axis = -1)        
print ("Sorted array along axis=-1:\n",arr2)

# Output:
# Original array:
#  [[12 15  7]
#  [13  5 11]
#  [ 8  6 10]
#  [45 54 70]]
# Sorted multi-dimensional array:
# [[ 7 12 15]
#  [ 5 11 13]
#  [ 6  8 10]
#  [45 54 70]]

4.1 Sort Multi-Dimensional Arrays Along Specified Axis

Sorting multi-dimensional arrays along a specified axis can be achieved using the numpy.sort() function with the axis parameter. If you pass a multi-dimensional array as a parameter of numpy.sort() along a specified axis with the value None, it will flatten 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. For instance, np.sort(arr, axis=0) sorts the array arr along the first axis (axis=0), which corresponds to sorting each column independently. The result is stored in arr2


# Sort along the first axis (axis=0)
arr2 = np.sort(arr, axis=0)
print("Sorted array along axis=0:\n",arr2)

# Output:
# Sorted array along axis=0:
# [[ 8  5  7]
# [12  6 10]
# [13 15 11]
# [45 54 70]]

Similarly, you pass a multi-dimensional array as a parameter of sort() along a specified axis with the value 1, which will sort the array in ascending order row-wise. For instance, np.sort(arr, axis=1) sorts the array arr along the second axis (axis=1), corresponding to sorting each row independently. The result is stored in arr3.


# Sort along the second axis (axis=1)
arr3 = np.sort(arr, axis=1)
print("Sorted array along axis=1:\n", arr3)

# Output:
# Sorted array along axis=1:
# [[ 7 12 15]
#  [ 5 11 13]
#  [ 6  8 10]
#  [45 54 70]]

5. Sort Different Types of 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.

To sort a 2D NumPy array of strings alphabetically. The np.sort(arr) function sorts each row of the 2D array independently, arranging the strings in lexicographical order within each row.


# Create a 2D NumPy array
arr = np.array([['orange','mango','grapes'], ['banana','cherry','apple'], ['papaya','watermelon','jackfruit']]) 

# Sort the array alphabetically
arr2 = np.sort(arr) 
print("Sorted array of strings:\n",arr2)

# Output:
# Sorted array of strings:
#  [['grapes' 'mango' 'orange']
#  ['apple' 'banana' 'cherry']
# ['jackfruit' 'papaya' 'watermelon']]

You can sort an array with boolean values using the numpy.sort() function. For example, np.sort(arr_bool) sorts the array of boolean values in ascending order. False comes before True in lexicographical order, so the sorted array has False first, followed by True.


# Create a NumPy array with boolean values
arr_bool = np.array([True, False, True, True, False, True])
print("Original array with boolean values:\n", arr_bool)

# Sorted array with boolean values
sorted_arr_bool = np.sort(arr_bool)
print("Sorted array with boolean values:\n", sorted_arr_bool)

# Output:
# Original array with boolean values:
#  [ True False  True  True False  True]
# Sorted array with boolean values:
#  [False False  True  True  True  True]

Frequently Asked Questions

How do I sort a NumPy array in ascending order?

You can use the numpy.sort() function to get a sorted copy of the array. If you want to sort the array in-place, you can use the sort() method of the NumPy array.

Can I sort a NumPy array in descending order?

You can sort a NumPy array in descending order. You can achieve this by using the numpy.sort() function to get a sorted copy and then reversing the order of the elements. You can achieve this by using the [::-1] slicing to reverse the order of the sorted array.

How do I sort a 2D NumPy array along a specific axis?

To sort a 2D NumPy array along a specific axis, you can use the numpy.sort() function and specify the desired axis using the axis parameter.

Can I sort a NumPy array of strings?

You can certainly sort a NumPy array of strings using the numpy.sort() function. The numpy.sort() function will sort the strings lexicographically in ascending order.

Does numpy.sort() modify the original array?

The numpy.sort() function does not modify the original array. Instead, it returns a sorted copy of the input array. If you want to sort the array in-place (i.e., modify the original array), you can use the sort() method of the NumPy array itself.

Conclusion

In this article, I have explained how to sort Numpy array/arrays using the numpy.sort() function with examples. Also, I have explained how to sort Multi-Dimensional array values along with a specified axis value.

Happy Learning!!

References

Malli

Malli is an experienced technical writer with a passion for translating complex Python concepts into clear, concise, and user-friendly articles. Over the years, he has written hundreds of articles in Pandas, NumPy, Python, and takes pride in ability to bridge the gap between technical experts and end-users.

Leave a Reply