bhylu.com

Advertisements

NumPy Sorting

sort returns ordered values, while argsort returns the positions that would produce that order. Use the positions when labels must move with measurements.

How it works

Sorting a measurement array without its associated labels can silently assign values to the wrong sites. A stable ordering is useful when ties should preserve an existing sequence. Choose the axis explicitly for multidimensional data. Sorting in place through an array method also differs from returning a separate sorted array through np.sort, so document whether the original order must survive.

Run the code

Select Try in playground to preload the complete code into the NumPy editor. Nothing executes on import; choose Run when ready. The first execution loads the local Pyodide runtime and NumPy package. Each ordinary run starts fresh, with no access to this page’s cookies or personal files. In-memory streams and temporary virtual files belong to the runtime, not your PC.

For local work, use a separate virtual environment and run python sorting.py. Download the complete source. The reviewed local environment uses Python 3.12.14 and NumPy 2.5.4; the browser uses Pyodide 0.27.7 with NumPy 2.0.2. Compatible examples are checked in both. See the environment setup. No Apache or database server is required.

Example

sorting.py

import numpy as np

litres = np.array([24, 12, 18])
sites = np.array(["west", "east", "north"])
order = np.argsort(litres, kind="stable")
print(litres[order].tolist())
print(sites[order].tolist())
print(litres.tolist())

Expected result

[12, 18, 24]
['east', 'north', 'west']
[24, 12, 18]

The same permutation keeps site names aligned with the ordered measurements. The original array retains its incoming order. A result that looks numerically sorted can still be wrong if the associated identifiers were left behind.

Use NumPy’s official reference for precise contracts, supported versions and numerical limitations.