Skip to content

numpy/int-mask-as-index

Rule int-mask-as-index
Pack NumPy
Severity error
Fix unsafe, with xpd check --fix --unsafe-fixes
Library versions every version

mask.astype(int) turns a mask into 0s and 1s, so indexing with it picks element 0 and element 1 over and over. Index with the mask itself.

large = y[(y > 15).astype(int)]
large = y[y > 15]

The rule reports y[(y > 15).astype(int)], which picks element 0 and element 1 over and over. It also reports ~(y > 15).astype(int), which gives -1 and -2.

The rule leaves alone a lookup such as labels[(score > t).astype(int)], where the mask comes from another array. Such a lookup maps each value to one of two labels.

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 y[y > 15]. The ~ form has no fix.

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

$M.astype($T) turns the mask into 0s and 1s, so this index picks element 0 and element 1 over and over. Index with the mask itself, $X[$M].

Browse the other rules of the NumPy pack.