Skip to content

pandas/nested-np-where

Rule nested-np-where
Pack pandas
Severity warning
Fix none, edit by hand
Library versions every version

Nested np.where calls read from the inside out and build an array for every level. Use Series.case_when, or pd.cut for numeric bins.

band = np.where(df["load"] < 20, "low", np.where(df["load"] < 70, "mid", "high"))
band = pd.Series("high", index=df.index).case_when([
(df["load"] < 20, "low"),
(df["load"] < 70, "mid"),
])

The rule reports np.where(a < 20, "low", np.where(a < 70, "mid", "high")).

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

case_when uses the first condition that matches, and it returns a Series instead of a NumPy array.

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

Nested np.where reads inside out and builds an array per level. Use Series.case_when, or pd.cut for numeric bins.

Browse the other rules of the pandas pack.