Reference · Vectors

vec.argsort

signature
vec.argsort(list | null, bool=) -> list

What it does

The positions that would put a list of numbers in ascending order: vec.argsort([30, 10, 20]) is [1, 2, 0], since item 1 is the smallest. With true as the second argument the order is descending. Equal items keep their order. Index another list by these positions to sort it the same way, which is how to sort names by their scores.

Examples

print(vec.argsort([30, 10, 20]))print(vec.argsort([30, 10, 20], true))let xs = [30, 10, 20]print(vec.argsort(xs) | map((i) => xs[i]))
output
[1, 2, 0][0, 2, 1][10, 20, 30]

Edge cases

print(vec.argsort([1, 1, 0]), vec.argsort([1, 1, 1], true))print(vec.argsort([]), vec.argsort(null))print(vec.argsort([float("nan"), 1, 2]))print(vec.argsort([2.5, 1, 2]))
output
[2, 0, 1] [0, 1, 2][] [][1, 2, 0][1, 2, 0]

Errors

An item that is not an int or a float, or an argument that is not a list, is a runtime error, not an error value. Strings are not sorted this way; use sort or sort_by.

this one fails
print(vec.argsort(["b", "a"]))
output
line 1: `vec.argsort` expects a list of numbers, but item 0 is str

Chaining

The descending positions give a ranking; the first is the top:

let names = ["ann", "bob", "cy"]let scores = [71, 88.5, 64]print(vec.argsort(scores, true) | map((i) => names[i]))print(scores | vec.argsort(true) | first)
output
["bob", "ann", "cy"]1

See also

vec.argmin, vec.argmax, sort, sort_by, stats.rank

Thread
7Useful? Like it, or add to its thread below.

Thread 0 posts

On vec.argsort(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo