bhylu.com

Advertisements

NumPy where and out

A ufunc’s where parameter decides which positions are calculated. Supply an initialized out array when the other positions need a defined value.

How it works

np.where selects between result values, but its arguments are evaluated before selection; it does not prevent a division expression from running. np.divide with where and out can express a controlled zero-denominator policy directly. This example chooses NaN for an undefined rate and calculates only where the duration is positive. A different application might reject the row instead; make that choice explicit.

Run the code

Select Try in playground to preload the complete code into the NumPy editor. Nothing executes on import; choose Run when ready. The first execution loads the local Pyodide runtime and NumPy package. Each ordinary run starts fresh, with no access to this page’s cookies or personal files. In-memory streams and temporary virtual files belong to the runtime, not your PC.

For local work, use a separate virtual environment and run python where-out.py. Download the complete source. The reviewed local environment uses Python 3.12.14 and NumPy 2.5.4; the browser uses Pyodide 0.27.7 with NumPy 2.0.2. Compatible examples are checked in both. See the environment setup. No Apache or database server is required.

Example

where-out.py

import numpy as np

litres = np.array([12., 18., 24.])
hours = np.array([2., 0., 4.])
rates = np.full(3, np.nan)
np.divide(litres, hours, out=rates, where=hours > 0)
print(rates[[0, 2]].tolist())
print(np.isnan(rates[1]))

Expected result

[6.0, 6.0]
True

The valid rates are six litres per hour and the undefined position stays NaN. Initializing out prevents an uncalculated position from containing arbitrary memory. The source arrays remain available for diagnosing the rejected duration.

Use NumPy’s official reference for precise contracts, supported versions and numerical limitations.