Experimental Copy-on-Write

Pandas 2.0 introduces an opt-in Copy-on-Write (CoW) mode. With CoW enabled, operations that appear to return a copy actually share memory until the first modification, eliminating SettingWithCopyWarning and reducing memory usage.

Enabling and Using CoW

python
import pandas as pd

# Enable Copy-on-Write
pd.set_option('mode.copy_on_write', True)

df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})

# This shares memory (no copy)
subset = df[['a']]

# Copy happens only on modification
subset.iloc[0, 0] = 999  # copy triggered here

# Original is NOT modified
print(df['a'].iloc[0])  # 1 (unchanged)
print(subset['a'].iloc[0])  # 999

# No more SettingWithCopyWarning!

Sources