Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn Array Sort

Sorting NumPy arrays can be done using the numpy.sort() function or the array.sort() method.


numpy.sort() Function: :This function returns a sorted copy of the input array along the specified axis. It does not modify the original array.

import numpy as np
arr = np.array([3, 1, 2, 5, 4])
# Sort the array
sorted_arr = np.sort(arr)
print(sorted_arr)


Output

[1 2 3 4 5]


Array.sort Method : This method sorts the array in-place, modifying the original array.

import numpy as np
arr = np.array([3, 1, 2, 5, 4])
# Sort the array in-place
arr.sort()
print(arr)


Output

[1 2 3 4 5]


You can also specify the axis parameter to sort along a specific axis for multi-dimensional arrays. By default, the axis parameter is None, which means the array is flattened before sorting.


import numpy as np
arr = np.array([[3, 1, 2], [5, 4, 6]])
# Sort along the first axis (rows)
sorted_arr_axis0 = np.sort(arr, axis=0)
# Sort along the second axis (columns)
sorted_arr_axis1 = np.sort(arr, axis=1)
print("Sorted along axis 0:")
print(sorted_arr_axis0)
print("\nSorted along axis 1:")
print(sorted_arr_axis1)


Output

Sorted along axis 0:
[[3 1 2]
[5 4 6]]
Sorted along axis 1:
[[1 2 3]
[4 5 6]]


These are the basic ways to sort NumPy arrays. Depending on your needs, you can choose between sorting the array in-place or creating a sorted copy using the appropriate method.





Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java