Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Sorting data is a core algorithmic primitive in numerical computing. In scientific pipelines, sorting enables ranking, percentile calculation, quantile binning, nearest-neighbor searches, and ordering multi-column tables.
NumPy provides two complementary sorting paradigms:
np.sort() / arr.sort()): Reorders and returns the actual values.np.argsort()): Returns the indices that would sort the array, enabling simultaneous sorting of multiple associated datasets.np.sort(arr): Returns a sorted copy of the array, leaving the original array completely untouched.arr.sort(): Sorts the array in-place directly within its existing memory buffer, returning None.When sorting multi-dimensional arrays, you can specify the target axis along which elements are ordered:
Output:
np.argsort()In real-world data science, you rarely sort a single isolated column. Instead, you have parallel arrays—such as employee names, salaries, and performance ratings—and sorting by salary must reorder the names and ratings in identical order.
np.argsort() returns the array of integer indices that put the array into sorted order:
To sort in descending order (highest first), slice the resulting indices with [::-1]:
np.lexsort()When sorting by multiple columns (e.g. sort primarily by Surname, and secondarily by First Name):
np.lexsort(): The keys are passed as a tuple, and the LAST key in the tuple is the PRIMARY sort key!Output:
arr.sort()?np.argsort(arr) return?salaries = np.array([50000, 30000, 80000]), what is the output of np.argsort(salaries)?np.lexsort((col_b, col_a)), which column acts as the primary sort key?np.sort()?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.