How to sort a Numpy Array

Published on Aug. 22, 2023, 12:15 p.m.

To sort a NumPy array in Python , you can use the sort() method of a NumPy ndarray object. Here’s an example that sorts a one-dimensional NumPy array:

import numpy as np

# Create a one-dimensional NumPy array
arr = np.array([3, 1, 4, 1, 5, 9, 2, 6])

# Call the sort() method to sort the array in ascending order
arr.sort()

# Print the sorted array to the console
print(arr)

In this example, we first create a one-dimensional NumPy array using the np.array() function. We then call the sort() method of the array to sort it in ascending order. Finally, we print the sorted array to the console using the print() function.

If you want to sort a multidimensional array, you can specify the axis along which the array should be sorted using the axis parameter of the sort() method.

Tags: