Sub topic 10
Migrating Code from pandas 2.x
This chapter assumes you know the Copy-on-Write rule from earlier chapters: a derived object never changes the object it came from. You should also be comfortable with .loc, .iloc, and basic NumPy arrays. Here you will find the code that behaves differently in pandas 3 and fix it.
What changes when you upgrade
In pandas 2.x, some code worked only because of view behavior. A slice or column could write through to its parent, depending on how it was built. pandas 3 removes that behavior. Most code keeps working, but three patterns break:
- Chained assignment such as
df["a"][0] = 100no longer updatesdf. - In-place methods on a derived object, such as
df["a"].fillna(0, inplace=True), no longer updatedf. - Code that writes into the array returned by
to_numpy()or.valuesnow fails, because the array is read-only.
The first two fail silently in the sense that the parent stays unchanged. That is why you should find them before you upgrade, not after.
A safe upgrade path
Work through the steps in order:
- Upgrade to the latest pandas 2.x release. Fix any deprecation warnings it reports first.
- Turn on the warning mode, described below.
- Run your tests and key scripts. Each warning points at code whose result will change.
- Rewrite that code, then repeat until no warnings remain.
- Upgrade to pandas 3 and run the tests again.
Finding problems with warn mode
pandas 2.2 and later can warn about every place where Copy-on-Write would change the result:
import pandas as pd
pd.options.mode.copy_on_write = "warn"
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
df["a"][0] = 100 # warns: this chained assignment will stop workingRun this on pandas 2.x, not pandas 3. In pandas 3 the option is not needed, because Copy-on-Write is the only behavior. Chained assignment there raises a ChainedAssignmentError warning, and the original is left unchanged.
Rewrite chained assignment
Replace each chain with one .loc call that names the rows and the column together:
import pandas as pd
df = pd.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
# Before (pandas 2.x, unreliable):
# df[df["foo"] > 1]["bar"] = 100
# After:
df.loc[df["foo"] > 1, "bar"] = 100
print(df)Rewrite in-place methods on derived objects
The inplace=True flag changes the object it is called on. When that object is df["a"], it is a derived object, so df stays the same. Assign the result back instead:
import pandas as pd
df = pd.DataFrame({"a": [1.0, None, 3.0]})
# Before: df["a"].fillna(0, inplace=True) # df is unchanged in pandas 3
df["a"] = df["a"].fillna(0)
print(df["a"].tolist()) # [1.0, 0.0, 3.0]The same fix applies to replace, clip, where, and similar methods. Assigning back is also clearer to read, because the line shows which object changes.
Handle read-only arrays
Under Copy-on-Write, to_numpy() and .values can return an array that shares memory with the DataFrame. pandas marks it read-only so a write cannot corrupt the DataFrame. Code that modifies such an array raises ValueError: assignment destination is read-only.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
arr = df["a"].to_numpy().copy() # explicit copy, safe to write
arr[0] = 100
print(df["a"].iloc[0]) # 1If you want the change in the DataFrame, write to the DataFrame with .loc or .iloc instead.
Remove defensive copies
In pandas 2.x, many people wrote .copy() after every slice to avoid SettingWithCopyWarning. Under Copy-on-Write that warning no longer exists, and every derived object already acts as a copy. Delete these calls where you only wanted to protect the parent:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
# Before: subset = df[df["a"] > 1].copy()
subset = df[df["a"] > 1]
subset.loc[subset.index[0], "b"] = 0 # df is not affectedKeep .copy() where you need a real copy of a NumPy array, as in the previous section.
Quick reference
| Pandas 2.x pattern | pandas 3 replacement |
|---|---|
| `df["a"][0] = 1` | `df.loc[0, "a"] = 1` |
| `df[mask]["b"] = 1` | `df.loc[mask, "b"] = 1` |
| `df["a"].fillna(0, inplace=True)` | `df["a"] = df["a"].fillna(0)` |
| `df.values[0, 0] = 1` | `df.iloc[0, 0] = 1` |
| `sub = df[mask].copy()` | `sub = df[mask]` |
Exercise
This pandas 2.x code runs without error, but after upgrading to pandas 3 the "price" column is never changed. Rewrite it so it works. df[df["qty"] == 0]["price"] = 0 df["price"].fillna(1, inplace=True)
Show answer
Both lines modify derived objects. Use one .loc call for the first line and assign back for the second: df.loc[df["qty"] == 0, "price"] = 0 df["price"] = df["price"].fillna(1)
Exercise
A function calls arr = df["a"].to_numpy() and then sets arr[0] = 5. It raises "assignment destination is read-only" in pandas 3. Give two fixes, and say how they differ.
Show answer
Fix 1: arr = df["a"].tonumpy().copy(), then write to arr. The DataFrame is not changed. Fix 2: write to the DataFrame directly with df.iloc[0, df.columns.getloc("a")] = 5. The DataFrame is changed. Choose by whether the DataFrame should change.