Sorting is a fundamental operation in data processing. NumPy provides efficient functions to sort arrays in various ways — along axes, in ascending or descending order, and more.
np.sort()
— Returns a sorted copy of an array without modifying the original.ndarray.sort()
— Sorts the array in-place, modifying the original array.np.argsort()
— Returns the indices that would sort an array.sorted_array = np.sort(array, axis=-1, kind='quicksort', order=None)
axis
parameter determines the axis along which to sort:
axis=-1
(default): Sorts along the last axis.axis=0
: Sorts each column (for 2D arrays).axis=1
: Sorts each row (for 2D arrays).axis=None
: Flattens the array before sorting.kind
specifies the sorting algorithm:
'quicksort'
— Fast but unstable (default).'mergesort'
— Stable sort.'heapsort'
— Not stable.'stable'
— Stable sort, available in newer versions.import numpy as np
# Example 1: Sort a 1D array (returns sorted copy)
arr = np.array([3, 1, 4, 1, 5, 9, 2])
sorted_arr = np.sort(arr)
print("Original array:", arr)
print("Sorted array:", sorted_arr)
# Output:
# Original array: [3 1 4 1 5 9 2]
# Sorted array: [1 1 2 3 4 5 9]
# Example 2: Sort a 2D array along rows (axis=1)
arr_2d = np.array([[3, 7, 5], [9, 1, 4]])
sorted_rows = np.sort(arr_2d, axis=1)
print("\nSorted each row:")
print(sorted_rows)
# Output:
# [[3 5 7]
# [1 4 9]]
# Example 3: Sort a 2D array along columns (axis=0)
sorted_cols = np.sort(arr_2d, axis=0)
print("\nSorted each column:")
print(sorted_cols)
# Output:
# [[3 1 4]
# [9 7 5]]
# Example 4: In-place sorting using ndarray.sort()
arr2 = np.array([10, 7, 8, 6, 9])
print("\nBefore in-place sort:", arr2)
arr2.sort()
print("After in-place sort:", arr2)
# Output:
# Before in-place sort: [10 7 8 6 9]
# After in-place sort: [ 6 7 8 9 10]
# Example 5: Using argsort() to get indices that would sort the array
arr3 = np.array([50, 10, 20, 40])
indices = np.argsort(arr3)
print("\nIndices that sort the array:", indices)
print("Sorted array using indices:", arr3[indices])
# Output:
# Indices that sort the array: [1 2 3 0]
# Sorted array using indices: [10 20 40 50]
[::-1]
on the sorted array: np.sort(arr)[::-1]
order
parameter.axis
values that do not exist in the array shape causes AxisError
.np.sort()
returns a sorted copy without modifying the original array.ndarray.sort()
sorts the array in-place.np.argsort()
returns indices to sort the array, useful for indirect sorting.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!