Skip to content

pandas/len-of-filter

Rule len-of-filter
Pack pandas
Severity warning
Fix unsafe, with xpd check --fix --unsafe-fixes
Library versions every version

len(df[mask]) builds a filtered frame only to count its rows. Sum the mask instead, as in int(mask.sum()).

count = len(df[df["load"] > 50])
count = int((df["load"] > 50).sum())

The rule reports len(df[df["a"] > 50]), which builds a filtered frame only to count its rows. The frame must be a plain name, and the rule doesn't run on test files.

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 int((df["a"] > 50).sum()).

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

Sum the mask instead of building the filtered frame to count it. Write int(($MASK).sum()).

Browse the other rules of the pandas pack.