Skip to content

numpy/sort-then-select

Pack Severity Fix Versions
NumPy warning unsafe, with xpd check --fix --unsafe-fixes All versions

Sorting every value to read the smallest or largest few was up to 39 times slower. Use np.min, np.max, np.partition or np.argpartition.

top = np.sort(scores)[-5:]
top = np.sort(np.partition(scores, -5)[-5:])

The rule reports np.sort(x)[0], np.sort(x)[-1], np.sort(x)[:5], np.sort(x)[-5:], np.sort(x)[::-1][:5], x[np.argsort(x)], np.argsort(x)[0], np.argsort(x)[-1], np.argsort(x)[:5], np.argsort(x)[-5:] and np.argsort(np.argsort(x)), with a literal count under 100.

xpd check --fix --unsafe-fixes applies the fixes of this rule. Check the result, because an unsafe fix can change what the code does.

The unsafe fix writes np.min(x), np.max(x), np.sort(np.partition(x, 5)[:5]), np.sort(np.partition(x, -5)[-5:]), np.sort(x), np.argmin(x), np.argmax(x). The positions of the k smallest or largest and the rank by a double argsort have no fix.

The reductions can propagate NaNs that sorting put last. They can also change which tied position is chosen or the sign of a zero. On multidimensional arrays, the original indexing can select a row. Check that the input has more than k elements before using partition.

This sorts every value to read the smallest one, which ran 39 times slower on 1,000,000 values. Write $NP.min($X).

See all rules in the NumPy pack.