ML Foundations

Why numpy.where does not skip calculations

Use the divide ufunc's where mask when a branch must avoid invalid arithmetic.

Example results for Why numpy.where does not skip calculations. np.where: 0.0, 0.5, -0.25
Illustration: Original illustration by Tensor Almanac
Evidence and testing

Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.

np.where selects results after arguments are evaluated

`np.where(condition, x, y)` chooses values from `x` and `y` element by element. It does not make Python evaluate those arguments lazily. In `np.where(values != 0, 1 / values, 0)`, Python computes `1 / values` before calling `np.where`, so zero entries can still trigger division warnings or infinities. [1, 2]

The returned array may look correct because the zero branch replaces the selected result, but the unused expression has already run. Hiding a warning with `np.errstate` changes reporting; it does not skip the division. The example runs both expressions under a narrow warning context, then compares their returned values. [1]

References: [1], [2]

Use the ufunc mask to skip selected operations

For elementwise division, call `np.divide` with `where=mask` and provide `out`. NumPy applies the operation only where the mask is true; where it is false, the corresponding output slot retains its existing value. Initializing `out` to zero therefore gives a deliberate zero for masked entries. [3]

Keep the mask shape compatible with NumPy broadcasting, and choose the output dtype deliberately when integer inputs or non-integer results are involved. This pattern is useful when excluded positions must not perform the operation at all, not merely have their result discarded afterward. [3]

References: [3]

Read the example as a behavior check

The fixture uses zero, positive, and negative denominators. Both arrays contain the same displayed values, but the code paths differ: `np.where` receives a division expression that has already run, while `np.divide` receives a mask that controls the ufunc operation. The example suppresses the warning only so its captured output stays concise; it is not the recommended fix. [1, 2, 3]

If the fallback should be `NaN`, a sentinel, or a domain-specific value, initialize `out` to that value before calling the ufunc. Do not leave masked output positions uninitialized. For a different operation, use that operation's own `where=` parameter when it exposes one. [3]

Executed with Python 3.12.14 and NumPy; stdout captured.

import numpy as np

values = np.array([0.0, 2.0, -4.0])
nonzero = values != 0

# np.where selects values after Python evaluates both arguments.
with np.errstate(divide="ignore"):
    selected = np.where(nonzero, 1.0 / values, 0.0)

# The ufunc mask skips division at positions where nonzero is false.
safe = np.zeros_like(values)
np.divide(1.0, values, out=safe, where=nonzero)

print("np.where:", selected.tolist())
print("np.divide where:", safe.tolist())

Recorded output

np.where: [0.0, 0.5, -0.25]
np.divide where: [0.0, 0.5, -0.25]

References: [1], [2], [3]

Sources

  1. Python function call evaluation
  2. NumPy where selection
  3. NumPy divide ufunc where parameter