Conditional selection & sorting in Python
Picking, clipping, and ordering array values without loops.
import numpy as np
scores = np.array([48, 92, 71, 30, 88, 65])
grades = np.where(scores >= 60, "pass", "fail")
clipped = np.clip(scores, 50, 90)
passing = scores[scores >= 60]
order = np.argsort(scores)
ranked = scores[order]
top_two = np.sort(scores)[-2:]
hit = np.nonzero(scores > 85)[0]
How it works
np.wherechooses per element from two options.clipbounds values; a mask filters them.argsortandsortorder the array.
Keywords and builtins used here
as
The run, in numbers
- Lines
- 13
- Characters to type
- 293
- Tokens
- 104
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 59 seconds.
Step 1 of 2 in Selection & random, step 7 of 22 in NumPy.