Sub topic 10
Migrating Code from pandas 2.x
This chapter assumes you know basic pandas, .loc and .iloc indexing, and Python references. You should also have read the earlier chapters on the Copy-on-Write (CoW) rule, chained assignment, lazy copies, and read-only arrays. Here you will apply that knowledge to an existing code base: how to find code that behaves differently in pandas 3, what to change, and how to check the result.
What changes and what does not
pandas 3 always uses Copy-on-Write. The rule is that a DataFrame or Series derived from another object never changes that object when you modify the derived one. Most 2.x code already follows this rule, because most code never relied on the old view behavior.
Three kinds of code break or change behavior:
- Code that modified a derived object and expected the original to change. Examples are chained assignment and in-place methods on a column.
- Code that wrote into a NumPy array obtained from
to_numpy()or.values, which is now read-only. - Code that still contains workarounds for the old view-or-copy ambiguity. These keep working, but they are now unnecessary.
Some things stay the same. If you pass a DataFrame to a function and that function runs df["x"] = 1 on its argument, the caller's DataFrame still changes. CoW governs objects derived from another object, not the same object seen through two names.
import pandas as pd
def add_flag(frame):
frame["flag"] = True # modifies the object the caller passed in
df = pd.DataFrame({"a": [1, 2, 3]})
add_flag(df)
print(df.columns.tolist()) # ['a', 'flag']The recommended migration path
Do not jump from an old 2.x release straight to pandas 3. Move in stages so each failure has one cause.
Step 1: upgrade to the latest 2.x release
Install the newest 2.x release first (2.3 at the time of writing). It contains the most complete set of deprecation warnings and the CoW warning mode. Run your test suite and fix every FutureWarning and DeprecationWarning that pandas raises. Fixing these before touching CoW keeps the two problems apart.
Step 2: use the warning mode
Since pandas 2.2 you can ask pandas to warn wherever CoW would change the result of your code. Add this near the start of your program or in your test configuration. It runs on 2.2 and 2.3 only, so do not keep it after the upgrade.
import pandas as pd
pd.options.mode.copy_on_write = "warn"
df = pd.DataFrame({"a": [1, 2, 3]})
df["a"][0] = 100 # in pandas 2.x with "warn", this emits a warningThe warning mode is a detector. It does not stop your code from running, and it can produce false positives. Some warnings point at code that would behave the same under CoW. Read each one and decide whether you relied on the old behavior.
To make the suite fail on the first problem, turn warnings into errors in your test runner. For pytest:
[tool.pytest.ini_options]
filterwarnings = [
"error::FutureWarning",
]This also turns unrelated future warnings into errors, so use it only after Step 1 is clean.
Step 3: switch CoW on without warnings
When the warning run is clean, set pd.options.mode.copy_on_write = True in 2.x and run the full test suite again. This is the same behavior you will get in pandas 3, so any remaining failure is a real difference, usually a read-only array or an update that no longer reaches the original.
Step 4: upgrade and clean up
Install pandas 3 and run the tests once more. Then remove the copy_on_write option from your code. In pandas 3 CoW is not optional, so setting it has no purpose. Finally, delete workarounds, as described later in this chapter.
Rewriting the patterns that break
Chained assignment
Chained assignment means two indexing operations in a row, with the assignment applied to the result of the first. The first operation returns a derived object, so the write lands there and never reaches df.
import pandas as pd
df = pd.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
# Before (pandas 2.x, unreliable; in pandas 3 it does nothing to df):
# df[df["foo"] > 1]["bar"] = 100
# After: one .loc call with a row selector and a column label
df.loc[df["foo"] > 1, "bar"] = 100
print(df)Expected output:
foo bar
0 1 4
1 2 100
2 3 100In pandas 3 the chained form emits a ChainedAssignmentError warning and leaves df unchanged. It is a warning, not an exception, so a script can run to the end with wrong data. To find these in a code base, search for assignments whose left side has two sets of brackets, or .loc[...] followed by more brackets:
df[...][...] = value
df.loc[...][...] = value
df[...].loc[...] = value
df[...].iloc[...] = valueYou can also let the tests find them. Make the warning an error:
[tool.pytest.ini_options]
filterwarnings = [
"error::pandas.errors.ChainedAssignmentError",
]Chained assignment spread over several lines
A common variant stores the intermediate result in a variable:
import pandas as pd
df = pd.DataFrame({"foo": [1, 2, 3], "bar": [4, 5, 6]})
subset = df[df["foo"] > 1]
subset["bar"] = 0 # modifies subset only
print(df["bar"].tolist()) # [4, 5, 6]Under 2.x this often triggered SettingWithCopyWarning and sometimes changed df. Under CoW it is not an error, and it never changes df. Decide what you meant:
- If you wanted to update
df, writedf.loc[df["foo"] > 1, "bar"] = 0. - If you wanted a separate result, keep the code as it is and delete any
.copy()you added only to silence the old warning.
SettingWithCopyWarning no longer exists in pandas 3. If your code sets pd.options.mode.chained_assignment, remove that line, because it no longer does anything useful.
In-place methods on derived objects
The same reasoning applies to methods with inplace=True. A column selected from a DataFrame is a derived object, so an in-place method on it changes only that object.
import pandas as pd
df = pd.DataFrame({"a": [1.0, None, 3.0], "b": [4, 5, 6]})
# Before: df["a"].fillna(0, inplace=True) # in pandas 3, df is unchanged
# After: assign the result back
df["a"] = df["a"].fillna(0)
# Or fill several columns in one call
df = df.fillna({"a": 0})
print(df["a"].tolist()) # [1.0, 0.0, 3.0]The same fix works for replace, clip, where, mask, and similar methods. Calling df.fillna(0, inplace=True) on the DataFrame itself still works. Only calls on an object derived from another one are affected. Many teams go further and drop inplace=True everywhere, because it saves no memory and prevents method chaining.
Writing into NumPy arrays
Arrays that expose pandas data are read-only. This affects to_numpy(), .values, and np.asarray(df). Writing to one raises ValueError: assignment destination is read-only.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
arr = df["a"].to_numpy()
print(arr.flags.writeable) # False
arr = df["a"].to_numpy().copy() # explicit copy
arr[0] = 100
print(df["a"].iloc[0]) # 1, df is unaffectedTwo fixes exist, and the choice depends on intent:
- If you want an independent array to work on, call
.copy()on the array, as above. You can also passcopy=Truetoto_numpy(). - If you wanted to change the DataFrame, write to the DataFrame with
.locor.iloc, then read the array again.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
df.iloc[0, 0] = 100 # update the DataFrame itself
arr = df["a"].to_numpy() # take the array after the update
print(arr[0]) # 100Libraries that mutate arrays they are given are the hard case, for example a C extension that writes to its input. Pass them a copy.
Code that relied on a shared view
Some old code modified a slice and expected the parent to change, or modified the parent and expected a slice to follow.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
head = df.iloc[:2] # in pandas 1.x/2.x this could be a view
df.loc[0, "a"] = 100
print(head["a"].iloc[0]) # 1 in pandas 3, head never sees the changeUnder CoW, head keeps the data it had when you created it. Tests that checked head after changing df will now fail, and they will fail in the correct direction. Review any code where one name is derived from another and both are modified later. If the program needs the update to show up, recompute the derived object after the change.
Removing workarounds
After the upgrade, clean up code written to avoid the old ambiguity.
| Old pattern | What to do in pandas 3 |
|---|---|
| `df2 = df[cols].copy()` before modifying `df2` | Remove `.copy()`. The write copies lazily. |
| `df.copy()` at the top of every helper "to be safe" | Remove it unless the function must not modify its argument in place. |
| `pd.options.mode.chained_assignment = None` | Remove it. The option no longer does anything useful. |
| `pd.options.mode.copy_on_write = True` | Remove it. CoW is always on. |
| `copy=False` or `copy=True` keyword on methods such as `reset_index` | Remove it where pandas flags it as deprecated. The keyword no longer has an effect. |
| `warnings.filterwarnings("ignore", category=SettingWithCopyWarning)` | Remove it. The class is gone. |
Keep a .copy() in two cases. The first is a function that modifies its argument but must not change the caller's object. The second is a NumPy array that you need to write to. In all other cases the copy only costs time and memory.
Checking the migrated code
A passing test suite is the main evidence. Add a few tests that pin down the new behavior, so a later change cannot bring back old assumptions. The test below checks that an update to a derived object leaves the original alone, and that the chained form emits the warning.
import warnings
import pandas as pd
def test_derived_object_does_not_change_parent():
df = pd.DataFrame({"a": [1, 2, 3]})
col = df["a"]
col.iloc[0] = 100
assert df["a"].iloc[0] == 1
def test_chained_assignment_warns():
df = pd.DataFrame({"a": [1, 2, 3]})
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
df["a"][0] = 100
assert any(w.category is pd.errors.ChainedAssignmentError for w in caught)
assert df["a"].iloc[0] == 1
if __name__ == "__main__":
test_derived_object_does_not_change_parent()
test_chained_assignment_warns()
print("ok")Also run the suite with -W error for a final pass, so that any warning pandas raises shows up as a failure.
Common mistakes during migration
- Silencing warnings instead of fixing them. A suppressed
ChainedAssignmentErrorleaves the update missing from your data. Rewrite the assignment. - Replacing the chain with another chain.
df.loc[mask]["bar"] = 1is still chained. The row selector and the column label belong in the same.loccall. - Copying arrays everywhere. Add
.copy()only where you write into an array. Reading from the read-only array needs no copy. - Trusting the warning mode alone. It warns about changed behavior, but it cannot see code paths your tests never run. Cover those paths before you rely on the result.
- Expecting performance changes to appear as bugs. Memory use often drops after the migration, because fewer copies are made. Treat that as a benefit and do not try to tune around it.
Exercise
This pandas 2.x code runs without error, but after upgrading to pandas 3 the NaN values in column "score" are still there. Rewrite it so it works in pandas 3. df = pd.DataFrame({"score": [1.0, None, 3.0], "name": ["a", "b", "c"]}) df["score"].fillna(0, inplace=True)
Show answer
The call modifies the Series df["score"], which is derived from df, so df itself is not changed (pandas 3 emits a ChainedAssignmentError warning). Assign the result back: df["score"] = df["score"].fillna(0). Using df = df.fillna({"score": 0}) also works.
Exercise
A helper does values = df["price"].to_numpy() and then values[values < 0] = 0. It works in pandas 2.x and raises a ValueError in pandas 3. Give two fixes and say which one changes df.
Show answer
Fix 1: take a copy before writing, values = df["price"].to_numpy().copy(). This leaves df unchanged. Fix 2: update the DataFrame directly, df.loc[df["price"] < 0, "price"] = 0. Only the second fix changes df, so choose it when the goal was to clean the data in df.
Exercise
List the four steps of a safe migration from pandas 2.x to pandas 3, in order.
Show answer
1. Upgrade to the latest 2.x release and fix its deprecation warnings. 2. Set pd.options.mode.copyonwrite = "warn", run the tests, and rewrite the flagged code. 3. Set it to True and run the tests again. 4. Upgrade to pandas 3, remove the copyonwrite option, and delete workarounds such as unneeded .copy() calls.