Skip to content

pandas/apply-arithmetic

Rule apply-arithmetic
Pack pandas
Severity warning
Fix unsafe, with xpd check --fix --unsafe-fixes
Library versions every version

Arithmetic inside apply runs Python once for every value. Write the same arithmetic on the whole column.

scaled = df["load"].apply(lambda value: value * 2 + 1)
scaled = df["load"] * 2 + 1

The rule reports df["b"].apply(lambda v: v * 2 + 1), which calls Python once per value where the same arithmetic on the column runs once. The fix is unsafe, because a column method returns a missing value where the lambda raised. The dtype can also change, as when dt.year gives int32 where the lambda gave int64.

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["b"] * 2 + 1.

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

Arithmetic per value runs in Python. Write $NEW on the whole column.

Browse the other rules of the pandas pack.