Universal functions and masked calculations
2.5.5
Apply operations element by element and protect calculations with an explicit mask.
On this page
Divide where the denominator is valid
A universal function, or ufunc, applies an operation element by element. In np.divide, where controls which entries are calculated. Initialize out to NaN so positions excluded by the mask retain a known value.
import numpy as np
orders = np.array([12, 0, 18])
visitors = np.array([60, 0, 90])
rate = np.full(visitors.shape, np.nan)
np.divide(orders, visitors, out=rate, where=visitors != 0)
print(rate.tolist())
Download image
Example output
[0.2, nan, 0.2]
Choose values with np.where
np.where(condition, x, y) selects values from x or y after its arguments have been evaluated. When the operation itself needs masking, such as division by zero, use the where argument of the ufunc.
import numpy as np
stock = np.array([3, 8, 0])
print(np.where(stock < 5, "Restock", "OK").tolist())
Example output
['Restock', 'OK', 'Restock']