Python:NumPy .sort()
The numpy.sort() method is a built-in NumPy function that returns a sorted copy of an array. It arranges the elements of an array in ascending order without modifying the original array, making it a fundamental tool for data organization and analysis in scientific computing and data science applications.
Syntax of numpy.sort()
numpy.sort(a, axis=-1, kind=None, order=None)
Parameters:
a: The input array to be sortedaxis: The axis along which to sort. IfNone, the array is flattened before sorting. Default is-1(sorts along the last axis)kind: Sorting algorithm. Options include'quicksort'(default),'mergesort','heapsort', or'stable'order: Specifies which fields to compare first when sorting structured arrays. Can be a string or list of strings
Return value:
Returns a sorted copy of the input array with the same type and shape as the original array.
Example 1: Basic Array Sorting Using numpy.sort() Method
The simplest use case of .sort() is sorting a one-dimensional array in ascending order:
import numpy as np# Create an array with unsorted numbersnumbers = np.array([64, 34, 25, 12, 22, 11, 90])# Sort the array in ascending ordersorted_numbers = np.sort(numbers)print("Original array:", numbers)print("Sorted array:", sorted_numbers)
The output of this code is:
Original array: [64 34 25 12 22 11 90]Sorted array: [11 12 22 25 34 64 90]
This example demonstrates the basic functionality of .sort() where it creates a new sorted array while leaving the original array unchanged. The method automatically arranges the elements from smallest to largest.
Example 2: Sorting Student Test Scores Using NumPy’s .sort()
This example shows how to sort student test scores to identify performance rankings and analyze grade distributions:
import numpy as np# Student test scores from a classtest_scores = np.array([85, 92, 78, 96, 88, 76, 91, 83, 87, 94])# Sort scores in ascending ordersorted_scores = np.sort(test_scores)# Get the lowest and highest scoreslowest_score = sorted_scores[0]highest_score = sorted_scores[-1]# Calculate median score (middle value)median_score = np.median(sorted_scores)print("Original scores:", test_scores)print("Sorted scores:", sorted_scores)print(f"Lowest score: {lowest_score}")print(f"Highest score: {highest_score}")print(f"Median score: {median_score}")
The output of this code is:
Original scores: [85 92 78 96 88 76 91 83 87 94]Sorted scores: [76 78 83 85 87 88 91 92 94 96]Lowest score: 76Highest score: 96Median score: 87
This example demonstrates how sorting test scores helps educators quickly identify the range of performance and calculate important statistics like median values.
Codebyte Example: Sorting Stock Prices by Date
This example shows how to sort daily stock prices to analyze market trends and identify patterns over time:
This example illustrates how sorting stock prices helps financial analysts understand market volatility and identify key price levels for investment decisions.
Frequently Asked Questions
1. Does .sort() modify the original array?
It depends which method you use: numpy.sort(array) returns a sorted copy without modifying the original, while array.sort() sorts the array in-place.
2. Can I sort arrays in descending order?
The .sort() method only sorts in ascending order. To get descending order, use np.sort(array)[::-1] to reverse the sorted array.
3. Can I sort multidimensional arrays?
Yes, use the axis parameter. numpy.sort(array, axis=0) sorts each column independently, while numpy.sort(array, axis=1) sorts each row independently.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours