Curriculum
Course: NumPy
Login

Curriculum

NumPy

Text lesson

NumPy Array Sort

Sorting Arrays

Sorting involves organizing elements in a specific order, such as numeric or alphabetical, either in ascending or descending sequence. The NumPy ndarray object provides a function called sort() that can sort a specified array.

Example

Arrange the array in order:

import numpy as np

arr = np.array([3201])

print(np.sort(arr))
Note: This method returns a copy of the array without modifying the original array.

You can also sort arrays containing strings or any other data type.

Example

Arrange the array in alphabetical order:

import numpy as np

arr = np.array([‘banana’‘cherry’‘apple’])

print(np.sort(arr))

Example

Arrange a boolean array:

import numpy as np

arr = np.array([TrueFalseTrue])

print(np.sort(arr))

Sorting a 2-D Array

If you apply the sort() method to a 2-D array, both dimensions will be sorted.

Example

Arrange a 2-D array in order:

import numpy as np

arr = np.array([[324], [501]])

print(np.sort(arr))