Sorting helps organize data so we can find patterns and answers faster. It makes comparing and analyzing data easier.
0
0
Why sorting matters in NumPy
Introduction
When you want to find the smallest or largest values quickly.
When you need to prepare data for searching or filtering.
When you want to see data trends by arranging values in order.
When you want to group similar data points together.
When you need to clean data by ordering it before removing duplicates.
Syntax
NumPy
numpy.sort(array, axis=-1, kind='quicksort', order=None)
array: The data you want to sort.
axis: The direction to sort (default is last axis).
Examples
Sort a simple 1D array in ascending order.
NumPy
import numpy as np arr = np.array([3, 1, 2]) sorted_arr = np.sort(arr) print(sorted_arr)
Sort a 2D array along rows (axis 0), sorting each column.
NumPy
arr2d = np.array([[3, 2], [1, 4]]) sorted_axis0 = np.sort(arr2d, axis=0) print(sorted_axis0)
Sort a 2D array along columns (axis 1), sorting each row.
NumPy
sorted_axis1 = np.sort(arr2d, axis=1) print(sorted_axis1)
Sample Program
This program shows how sorting helps us organize exam scores. We sort a list of scores to find the lowest and highest easily. Then, we sort a 2D array by subject to compare scores across students.
NumPy
import numpy as np # Create an array of exam scores scores = np.array([88, 92, 79, 93, 85]) # Sort scores to see who scored lowest to highest sorted_scores = np.sort(scores) print('Sorted scores:', sorted_scores) # Find the top 3 scores by sorting and slicing top_3 = sorted_scores[-3:] print('Top 3 scores:', top_3) # Sort a 2D array of student scores by subject scores_2d = np.array([[88, 92], [79, 93], [85, 90]]) sorted_by_subject = np.sort(scores_2d, axis=0) print('Scores sorted by subject (columns):\n', sorted_by_subject)
OutputSuccess
Important Notes
Sorting does not change the original array unless you assign the result back.
Use axis to control sorting direction in multi-dimensional arrays.
Sorting helps speed up searching and grouping tasks.
Summary
Sorting arranges data to make analysis easier and faster.
Use numpy.sort() to sort arrays along different axes.
Sorting is useful for finding top values, trends, and cleaning data.