Safe independent editing
You need to modify a derived DataFrame without changing the source.
Pandas · Module
Creates a new DataFrame from the caller’s data and indices. By default it copies them; deep=False creates a shallow copy, with Copy-on-Write protecting writes from affecting the other object.
Call copy() to create another DataFrame with copied data and indices by default. Passing deep=False creates a shallow copy that initially shares references, while Copy-on-Write prevents writes through either object from changing the other.
DataFrame.copy(deep=True)| Name | Type | Description |
|---|---|---|
deep | bool, default True | Controls whether the DataFrame's data and indices are copied. True makes a deep copy; False copies only references. |
DataFrame; the returned object type matches the caller.
import pandas as pd
original = pd.DataFrame({"score": [10, 20]})
copy = original.copy()
copy.loc[0, "score"] = 99
print(original.loc[0, "score"]) # 10
print(copy.loc[0, "score"]) # 99The default copy has independent data and index storage, so changing its scalar value does not change the original DataFrame.
You need to modify a derived DataFrame without changing the source.
You want a lightweight object sharing data and index references initially.
You need to isolate writes while avoiding eager duplication.
copy() returns a new object containing copies of the caller's data and indices by default because deep defaults to True. Changes to the copied data or indices are therefore not reflected in the original.
Follow-up: What does deep=True mean for objects stored in cells? It copies the container data but only copies references to nested Python objects, not those objects recursively.
deep=False creates a new DataFrame while copying neither the data nor the index; it copies references to them instead. The returned object still has the same type as its caller.
Follow-up: How does Copy-on-Write alter shallow-copy behavior? A write to either object causes the affected data to be copied, preventing the other object from observing that mutation.
The method returns a Series or DataFrame whose type matches the caller. For a DataFrame, this means copy() produces another DataFrame.
Follow-up: Why can an index's underlying array remain shared even with deep=True? Index objects are immutable, so sharing their underlying data is safe and avoids an unnecessary copy.
DataFrame.astypeDataFrame.ilocDataFrame.locDataFrame.copy