Ravindra Bagale · Data Scienceसर्व coursesया course चे lessonsशोधाEnglish

Data Science · मराठी आवृत्ती

23.1 SettingWithCopy आणि chained assignment

By Ravindra Bagale

या course चे सर्व chapters (py + ch)

हे का शिकायचं?

df[mask]["col"] = ... कधीकधी चालत नाही किंवा warning येते. Copy vs view गोंधळ.

हे काय आहे?

Fix: .loc[mask, "col"] = value वापरा. किंवा स्पष्ट .copy() नंतर assign.

कसं करायचं?

Step 1. Chained assignment ओळखा.

Step 2. .loc वापरा.

Step 3. गरज असल्यास .copy().

Step 4. Warning आली तर ignore करू नका — rewrite करा.

उदाहरणं: copy करा आणि चालवा

उदाहरण A — Broken vs fixed.

import pandas as pd

df = pd.DataFrame({
    "order_id": ["BLK-1", "BLK-2", "BLK-3", "AMN-4"],
    "city": ["Pune", "Pune", "Nashik", "Kolhapur"],
    "delivery_mins": [18, 22, 11, 10],
    "customer": ["Ruhi Bagale", "Amir", "Zoya", "Ravina"],
})

# Fragile — may not write back
df[df["city"] == "Pune"]["delivery_mins"] = 12
print("after chain", df["delivery_mins"].tolist())

# Clear — writes on df
df.loc[df["city"] == "Pune", "delivery_mins"] = 12
print("after loc", df["delivery_mins"].tolist())

उदाहरण B — Explicit copy for a side analysis.

pune = df.loc[df["city"] == "Pune"].copy()
pune["sla_flag"] = pune["delivery_mins"] <= 15
print(pune[["order_id", "sla_flag"]])
# original df has no sla_flag — intentional
print("sla in df?", "sla_flag" in df.columns)

उदाहरण C — New column with np.where.

import numpy as np

df = df.copy()
df["late"] = np.where(df["delivery_mins"] > 15, "Late", "OK")
print(df[["city", "delivery_mins", "late"]])

Raja in Nagpur uses the same pattern for cancel flags — one column, no chain.