Skip to content

numpy/where-shortcut

Rule where-shortcut
Pack NumPy
Severity warning
Fix unsafe, with xpd check --fix --unsafe-fixes
Library versions every version

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)

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].

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).

xpd prints this message with the issue. A name that starts with $ stands for code from your file.

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).

Browse the other rules of the NumPy pack.