Skip to content
Justice Tech School

copy and Chained Assignment

Use .copy() when you change a slice and use loc for assignment to avoid warnings.

Example
df = pd.DataFrame({"name": ["Ada", "Kofi", "Amina", "Tunde"], "country": ["NG", "GH", "NG", "NG"], "score": [92, 78, 85, 71]})
sub = df[df["country"] == "NG"].copy()
sub["score"] = sub["score"] + 1
print(sub["score"].tolist())
print(df["score"].tolist())

Result

[93, 86, 72]
[92, 78, 85, 71]

Exercise

Safe copy.

df[mask].()

Quiz Test

Why copy a slice?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.