Skip to content

pandas/copy-after-indexing

Rule copy-after-indexing
Pack pandas
Severity warning
Fix unsafe, with xpd check --fix --unsafe-fixes
Library versions every version

Under copy-on-write a selection already behaves as a copy, so .copy() after it only costs memory and time. Drop the .copy().

part = df[["load", "wind"]].copy()
part = df[["load", "wind"]]

The rule reports df[["a", "b"]].copy(), df[mask].copy() and df.loc[...].copy(), because under copy-on-write the selection already behaves as a copy. It leaves a single text label and a slice alone, because on a dict or a NumPy array the copy keeps a later write away from the original.

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 drops .copy(). Without the copy, .values and .to_numpy() of the result give an array that is read-only or shares memory with the source.

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

Copy-on-write already keeps later writes away from the original, so this copy only costs memory and time. Drop .copy().

Browse the other rules of the pandas pack.