Skip to content

pandas/index-loop

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

A loop over index labels that reads the frame with loc or at runs Python once for every row. Compute on whole columns instead.

out = []
for label in df.index:
out.append(df.loc[label, "load"] * df.loc[label, "weight"])
out = (df["load"] * df["weight"]).tolist()

The rule reports for label in df.index with df.loc[label, "a"] or df.at[label, "a"] in the body, also as a comprehension, which reads the frame one label at a time. It leaves a loop alone that never reads the frame by its label, and it doesn't run on test files.

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

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

A loop over index labels runs Python once per row. Compute on whole columns instead, such as df["a"] * df["w"].

Browse the other rules of the pandas pack.