Skip to content

pandas/mask-precedence

Rule mask-precedence
Pack pandas
Severity error
Fix unsafe, with xpd check --fix --unsafe-fixes
Library versions every version

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

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.

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

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

Browse the other rules of the pandas pack.