Skip to content

pandas/apply-condition

Rule apply-condition
Pack pandas
Severity warning
Fix none, edit by hand
Library versions every version

A condition inside apply runs Python once for every value. Use np.where(condition, a, b) on the whole column, or clip for a minimum or a maximum.

level = df["load"].apply(lambda value: "high" if value > 50 else "low")
level = pd.Series(np.where(df["load"] > 50, "high", "low"), index=df.index)

The rule reports df["a"].apply(lambda v: 1 if v > 50 else 0) and lambda v: min(v, 1.0). The rule leaves alone a lambda that reduces its argument, as in x.isnull().all(), because the lambda gets a whole Series per group.

xpd has no automatic fix, so make the change by hand.

pd.Series(..., index=df.index) keeps the row labels. Check the name, the dtype and the missing values of the result.

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

A condition per value runs in Python. Use np.where(condition, a, b) on the whole column, or clip for min and max.

Browse the other rules of the pandas pack.