Skip to content

pandas/mask-precedence

Pack Severity Fix Versions
pandas error unsafe, with xpd check --fix --unsafe-fixes All versions

Python applies & and | before comparisons, so df["a"] > 1 & df["b"] < 3 compares against the wrong value. Put each comparison in parentheses.

selected = df[df["load"] > 1 & df["wind"] < 3]
selected = df[(df["load"] > 1) & (df["wind"] < 3)]

The rule reports df["a"] > 1 & df["b"] < 3, where Python applies & before the comparisons, so the code compares df["a"] with 1 & df["b"]. The rule checks a bitwise operator to the right of a comparison operator. It leaves flags & 4 == 0 alone, and it leaves set operations in membership and identity comparisons alone.

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 (df["a"] > 1) & (df["b"] < 3). The fix closes the comparison before each & or | and opens it again after, so the result changes on purpose.

The & and | operators bind tighter than comparisons, so this compares against a combined value. Put each comparison in parentheses, as in (df["a"] > 1) & (df["b"] < 3).

See all rules in the pandas pack.