Skip to content

pandas/apply-cast

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

Casting with apply(int) or map(float) converts one value at a time in Python. Cast the whole column with astype.

whole = df["load"].apply(int)
whole = df["load"].astype(int)

The rule reports df["b"].apply(int), df["raw"].map(float) and df["b"].apply(lambda v: int(v)), which cast one value at a time. With a bare function name it reports apply only on a column taken by a text label. The rule covers int and float only, because on floats with missing values astype(str) was slower than apply(str) and kept the missing values.

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"].astype(int).

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

This calls $T once per value. Write $S.astype($T) on the whole column.

Browse the other rules of the pandas pack.