.sort()
Published Dec 19, 2024
Contribute to Docs
In NumPy, the .sort()
function sorts the elements of an array or matrix along a specified axis. It returns a new array with elements sorted in ascending order, leaving the original array unchanged. Sorting can be performed along different axes (such as rows or columns in a 2D array), with the default being along the last axis (axis=-1
).
Syntax
numpy.sort(a, axis=-1, kind=None, order=None)
a
: The array of elements to be sorted.axis
: The axis along which to sort. If set toNone
, the array is flattened before sorting. The default is-1
, which sorts along the last axis.kind
: The sorting algorithm to use. The options are:'quicksort'
: Default algorithm, a fast, comparison-based algorithm.'mergesort'
: Stable sort using a divide-and-conquer algorithm.'heapsort'
: A comparison-based sort using a heap.'stable'
: A stable sorting algorithm, typically mergesort.
order
: Ifa
is a structured array, this specifies the field(s) to sort by. If not provided, sorting will be done based on the order of the fields ina
.
Example
The following example demonstrates how to use the .sort()
function with various parameters:
import numpy as nparr = np.array([[3, 1, 2], [6, 4, 5]])print(np.sort(arr))print(np.sort(arr, axis=0))print(np.sort(arr, axis=None))
This example results in the following output:
[[1 2 3][4 5 6]][[3 1 2][6 4 5]][1 2 3 4 5 6]
Codebyte Example
Run the following codebyte example to better understand the .sort()
function:
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
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly90 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours