import numpy as np
Sorting NumPy ArraysΒΆ
np.sort() returns a sorted copy of an array, leaving the original unchanged. It works with numbers (ascending order), strings (alphabetical order), and booleans (False before True). For 2D arrays, sorting happens along the last axis by default β meaning each row is sorted independently. You can control this with the axis parameter. Sorting is fundamental to data analysis: ranking values, finding medians, identifying percentiles, and preparing data for binary search all depend on sorted arrays.
Sorting NumbersΒΆ
np.sort() arranges numeric elements in ascending order and returns a new sorted array. The original array remains unmodified β this non-mutating behavior is important for preserving raw data while working with sorted views.
Sorting Strings AlphabeticallyΒΆ
When applied to string arrays, np.sort() arranges elements in lexicographic (alphabetical) order. This is useful for organizing categorical data, creating ordered labels, or preparing string data for display.
Sorting BooleansΒΆ
Boolean arrays sort with False (0) values first and True (1) values second. This can be useful for partitioning data β separating items that meet a condition from those that do not.
# 2-D
np4 = np.array([[6,7,1,9], [4,3,0,8]])
print(np4)
print(np.sort(np4))