Skip to content

[Edit]: NumPy .sort() #7224

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 102 additions & 35 deletions content/numpy/concepts/built-in-functions/terms/sort/sort.md
Original file line number Diff line number Diff line change
@@ -1,79 +1,146 @@
---
Title: '.sort()'
Description: 'Sorts an array in ascending order along the specified axis and returns a sorted copy of the input array.'
Description: 'Returns a sorted copy of an array in ascending order.'
Subjects:
- 'Computer Science'
- 'Data Science'
Tags:
- 'Arrays'
- 'Functions'
- 'NumPy'
- 'Sorting Algorithms'
CatalogContent:
- 'learn-python-3'
- 'paths/data-science'
---

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`).
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.

The `numpy.sort()` method is essential for organizing data in a meaningful sequence, enabling efficient data analysis, pattern recognition, and preparation for algorithms that require sorted input. It is commonly used in statistical analysis, data preprocessing, search operations, and creating ordered datasets for visualization and reporting.

## Syntax

```pseudo
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 to `None`, 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'`](https://www.codecademy.com/resources/docs/general/algorithm/quick-sort): Default algorithm, a fast, comparison-based algorithm.
- [`'mergesort'`](https://www.codecademy.com/resources/docs/general/algorithm/merge-sort): Stable sort using a divide-and-conquer algorithm.
- [`'heapsort'`](https://www.codecademy.com/resources/docs/general/algorithm/heap-sort): A comparison-based sort using a heap.
- `'stable'`: A stable sorting algorithm, typically mergesort.
- `order`: If `a` 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 in `a`.
**Parameters:**

- `a`: The input array to be sorted
- `axis`: The axis along which to sort. If `None`, the array is flattened before sorting. Default is `-1` (sorts along the last axis)
- `kind`: Sorting algorithm. Options include [`'quicksort'`](<(https://www.codecademy.com/resources/docs/general/algorithm/quick-sort)>) (default), [`'mergesort'`](<(https://www.codecademy.com/resources/docs/general/algorithm/merge-sort)>), [`'heapsort'`](https://www.codecademy.com/resources/docs/general/algorithm/heap-sort), 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

The simplest use case of `.sort()` is sorting a one-dimensional array in ascending order:

```py
import numpy as np

# Create an array with unsorted numbers
numbers = np.array([64, 34, 25, 12, 22, 11, 90])

# Sort the array in ascending order
sorted_numbers = np.sort(numbers)

print("Original array:", numbers)
print("Sorted array:", sorted_numbers)
```

The output of this code is:

```shell
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
## Example 2: Sorting Student Test Scores

The following example demonstrates how to use the `.sort()` function with various parameters:
This example shows how to sort student test scores to identify performance rankings and analyze grade distributions:

```py
import numpy as np

arr = np.array([[3, 1, 2], [6, 4, 5]])
# Student test scores from a class
test_scores = np.array([85, 92, 78, 96, 88, 76, 91, 83, 87, 94])

# Sort scores in ascending order
sorted_scores = np.sort(test_scores)

print(np.sort(arr))
print(np.sort(arr, axis=0))
print(np.sort(arr, axis=None))
# Get the lowest and highest scores
lowest_score = sorted_scores[0]
highest_score = sorted_scores[-1]

# Calculate median score (middle value)
median_score = sorted_scores[len(sorted_scores) // 2]

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}")
```

This example results in the following output:
The output of this code is:

```shell
[[1 2 3]
[4 5 6]]
[[3 1 2]
[6 4 5]]
[1 2 3 4 5 6]
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: 76
Highest score: 96
Median score: 87
```

## Codebyte Example
This example demonstrates how sorting test scores helps educators quickly identify the range of performance and calculate important statistics like median values.

Run the following codebyte example to better understand the `.sort()` function:
## 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:

```codebyte/python
import numpy as np

arr = np.array([[23, 54, 19], [45, 34, 12]])
# Daily stock prices over two weeks (in dollars)
stock_prices = np.array([125.50, 127.20, 123.80, 128.90, 131.45,
129.70, 133.20, 130.15, 128.60, 132.80,
134.90, 131.25, 129.40, 135.70])

print("Original array:")
print(arr)
# Sort prices to analyze the range and distribution
sorted_prices = np.sort(stock_prices)

# Sort along axis 0 (sort by columns)
print("\nSorted array along axis 0 (columns):")
print(np.sort(arr, axis=0))
# Find the price range
price_range = sorted_prices[-1] - sorted_prices[0]

# Sort along axis 1 (sort by rows)
print("\nSorted array along axis 1 (rows):")
print(np.sort(arr, axis=1))
# Calculate quartiles for market analysis
q1 = sorted_prices[len(sorted_prices) // 4]
q3 = sorted_prices[3 * len(sorted_prices) // 4]

print("\nSorted array (flattened):")
print(np.sort(arr, axis=None))
print("Original prices:", stock_prices)
print("Sorted prices:", sorted_prices)
print(f"Price range: ${price_range:.2f}")
print(f"First quartile (Q1): ${q1:.2f}")
print(f"Third quartile (Q3): ${q3:.2f}")
```

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?

No, `.sort()` returns a sorted copy of the array while leaving the original array unchanged. To sort in-place, use the `.sort()` method directly on the array (e.g., `arr.sort()`).

### 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 to specify which axis to sort along. For example, `np.sort(array, axis=0)` sorts along rows, while `np.sort(array, axis=1)` sorts along columns.