numpy/count-nonzero
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| NumPy | warning | unsafe, with xpd check --fix --unsafe-fixes |
All versions |
Summing a comparison or taking the length of np.where counts matches the slow way. Call np.count_nonzero.
changed = np.sum(before != after)changed = np.count_nonzero(before != after)What the rule reports
Section titled “What the rule reports”The rule reports np.sum(x > 0), len(np.where(c)[0]), len(np.nonzero(c)[0]), len(np.flatnonzero(c)), len(x[x > 0]) and np.sum(x > 2) > 0. In a file that imports pandas, the pandas rule len-of-filter reports len(x[x > 0]) instead, because x may be a frame or a series.
The rule leaves chained comparisons such as np.sum(c > 0) > 0 == flag alone.
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 safe fix writes np.any(x > 2). The unsafe fix writes np.count_nonzero(x > 0), also for len(x[x > 0]), which gave a Python int.
np.count_nonzero counts masked values that np.sum skips and can raise on a pandas column with missing values. It can count a zero-dimensional array where one-argument np.where raises. With a dictionary, the original subscript can look up a key, so check that the expression is an array filter.
Diagnostic message
Section titled “Diagnostic message”Summing a comparison adds the True values one by one, which ran 1.7 times slower on 1,000,000 values. Write $NP.count_nonzero($C).See all rules in the NumPy pack.