Skip to content

pandas/apply-cast

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

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

The fix can change the result when a column holds Python objects whose integer or float conversion behaves differently when called directly.

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

See all rules in the pandas pack.