numpy/where-shortcut
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| NumPy | warning | unsafe, with xpd check --fix --unsafe-fixes |
All versions |
np.where(x > 0, True, False) copies a mask that is already an array of booleans, which was 17 times slower. Use the comparison itself.
relu = np.where(z > 0, z, 0)relu = np.maximum(z, 0)What the rule reports
Section titled “What the rule reports”The rule reports np.where(x > 0, True, False), np.where(x > 0, 1, 0), np.where(x > 0, x, 0), np.where(x < 0, 0, x) and np.arange(len(x))[x > 1].
How to fix it
Section titled “How to fix it”xpd check --fix --unsafe-fixes applies the fixes of this rule. Check the result, because an unsafe fix can change what the code does.
The unsafe fix writes np.asarray(x > 0), np.asarray(x > 0, dtype=int), np.maximum(x, 0), np.flatnonzero(x > 1).
np.maximum keeps NaNs that the conditional replaced with zero and can return a scalar where np.where returned a zero-dimensional array. A pandas column with missing values can produce a different exception or an object array. flatnonzero can return positions for a two-dimensional or oversized mask that the original indexing rejected.
Diagnostic message
Section titled “Diagnostic message”The comparison is already an array of True and False, and np.where copies it, which ran 17 times slower on 1,000,000 values. Write $NP.asarray($C).See all rules in the NumPy pack.