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)What the rule reports
Section titled “What the rule reports”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.
How to fix it
Section titled “How to fix it”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).
Message
Section titled “Message”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.