typestar

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

  1. np.where chooses per element from two options.
  2. clip bounds values; a mask filters them.
  3. argsort and sort order the array.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 2 in Selection & random, step 7 of 22 in NumPy.

← Previous Next →