Sub topic 8
In-place methods on columns and other derived objects
This chapter assumes you know how .loc and .iloc assignment works. It also assumes you have read the earlier chapters on the Copy-on-Write rule and chained assignment. You should be comfortable with Python references to mutable objects. NumPy knowledge is not needed here.
The earlier chapters showed that df["a"][0] = 100 stops updating df in pandas 3. This chapter covers the second half of that story: methods that modify an object in place, such as fillna(..., inplace=True), when you call them on something derived from a DataFrame. They fail for the same reason, and the failure is often harder to notice.
What "in place" means under Copy-on-Write
The Copy-on-Write rule says that any DataFrame or Series derived from another object behaves as an independent copy. Every one of these expressions creates a derived object:
df["a"]is a Series derived fromdf.df[["a", "b"]]is a DataFrame derived fromdf.df[df["b"] > 4]is a DataFrame derived fromdf.df.iloc[:2]is a DataFrame derived fromdf.df.loc[:, "a"]is a Series derived fromdf.
An in-place method changes the object it is called on and returns None. The method has no knowledge of where the object came from. If you call it on a derived object, it changes that derived object, and the parent stays untouched.
Before pandas 3, the result depended on whether pandas had decided to give you a view or a copy. Now the outcome is the same every time. An in-place method on a derived object never reaches the parent.
An in-place method on the DataFrame you actually want to change still works. df.fillna(0, inplace=True) modifies df because df is the object the method is called on.
A column is a derived object
This is the case that causes the most trouble. Take a column out of a DataFrame, call an in-place method on it, and look at both objects.
import pandas as pd
df = pd.DataFrame({"a": [1.0, None, 3.0], "b": [4, 5, 6]})
col = df["a"]
col.fillna(0, inplace=True)
print(col.tolist()) # [1.0, 0.0, 3.0]
print(df["a"].tolist()) # [1.0, nan, 3.0]col was filled. df still holds the missing value. In pandas 2.x with the old behavior, col could have been a view of df's memory, and this code might have updated both. Under Copy-on-Write it never does.
This version produces no warning. The variable col is a legitimate Series that you named and own. pandas cannot tell that you expected the change to reach df, so the bug is silent. Be especially careful with this pattern.
The direction also works the other way. A change to the parent does not reach a derived object you took earlier.
import pandas as pd
df = pd.DataFrame({"a": [1.0, None, 3.0], "b": [4, 5, 6]})
col = df["a"]
df.fillna(0, inplace=True)
print(df["a"].tolist()) # [1.0, 0.0, 3.0]
print(col.tolist()) # [1.0, nan, 3.0]df changed. col kept the values it had when you created it. If you treat col as a live window into df, you will read stale data.
Chained in-place calls
Now remove the variable and write the whole operation as one expression.
import warnings
import pandas as pd
df = pd.DataFrame({"a": [1.0, None, 3.0], "b": [4, 5, 6]})
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
df["a"].fillna(0, inplace=True)
print([w.category.__name__ for w in caught]) # ['ChainedAssignmentError']
print(df["a"].tolist()) # [1.0, nan, 3.0]Here df["a"] is a temporary Series that nothing else refers to. The in-place fillna modifies that temporary object, and it is thrown away a moment later. df is unchanged.
pandas notices that the object being modified is a temporary with no other references. It emits a ChainedAssignmentError warning to say the operation can never reach the parent. This is the same warning you saw for df["a"][0] = 100. The warning class is the same for chained setitem and for chained in-place methods.
The warning is a hint and not a guarantee. You get it when the object is an unreferenced temporary. You do not get it when you stored the derived object in a variable, as in the first example. Do not use the absence of a warning as proof that your code is correct.
Three supported ways to fill a column
There are three ways to write this so that df actually changes. They differ in what they cost and in what they say about your intent.
import pandas as pd
def make_df():
return pd.DataFrame({"a": [1.0, None, 3.0], "b": [4, 5, 6]})
# 1. Assign the result back to the column.
df = make_df()
df["a"] = df["a"].fillna(0)
print(df["a"].tolist()) # [1.0, 0.0, 3.0]
# 2. Call the method on the DataFrame, naming the column in a dict.
df = make_df()
df.fillna({"a": 0}, inplace=True)
print(df["a"].tolist()) # [1.0, 0.0, 3.0]
# 3. Use a single .loc assignment with a boolean mask.
df = make_df()
df.loc[df["a"].isna(), "a"] = 0
print(df["a"].tolist()) # [1.0, 0.0, 3.0]Option 1 is the most common rewrite. It reads clearly: compute a new column, then assign it. The assignment replaces the whole column in df, and the old column data is released.
Option 2 keeps the inplace=True style. It works because the method is called on df itself. Passing a dict to fillna limits the fill to the named columns.
Option 3 writes into the existing column using a single .loc call, as you saw in the assignment chapter. It is the right choice when only some rows change, because the mask selects them.
The same rewrites apply to other methods. For replace, either call df.replace({"a": {1: 10}}) on the DataFrame or assign df["a"] = df["a"].replace(1, 10). For clip, where and mask, assign the result back. drop and sort_values use the same logic, although they work on rows or columns rather than values.
The `None` trap
A common mistake combines both styles. You know that df["a"] = ... works, and you know fillna takes inplace=True, so you write both.
import pandas as pd
df = pd.DataFrame({"a": [1.0, None, 3.0], "b": [4, 5, 6]})
df["a"] = df["a"].fillna(0, inplace=True)
print(df["a"].tolist()) # [None, None, None]An in-place method returns None. The right-hand side evaluates to None, and assigning None to a column fills every row with None. The data in column a is gone. This mistake existed before pandas 3, and it still does, so check for it when you convert code.
Use one style or the other:
- Use
df["a"] = df["a"].fillna(0)for a returned value. - Use
df.fillna({"a": 0}, inplace=True)for an in-place change ondf.
Never combine them.
Other derived objects: subsets and slices
Columns are not the only derived objects. Any row subset, column subset or slice is derived too, and the same rule applies.
import pandas as pd
df = pd.DataFrame({"k": ["x", "y", "z"], "v": [3, 1, 2]})
subset = df[df["v"] > 1]
subset.sort_values("v", inplace=True)
print(subset["k"].tolist()) # ['z', 'x']
print(df["k"].tolist()) # ['x', 'y', 'z']subset is its own object. Sorting it in place reorders subset and leaves the row order of df alone. This is usually what you want, because you rarely mean to reorder the parent by sorting a filtered copy.
The risk is the opposite case, where you wanted the parent to change. Two examples show the intent and the supported way to write it.
| What you wanted | Code that no longer works | Supported rewrite |
|---|---|---|
| Fill missing values in one column of `df` | `df["a"].fillna(0, inplace=True)` | `df["a"] = df["a"].fillna(0)` |
| Replace values in one column of `df` | `df["a"].replace(1, 10, inplace=True)` | `df["a"] = df["a"].replace(1, 10)` |
| Change a column only for rows that match a condition | `df[df["b"] > 4]["a"] = 0` | `df.loc[df["b"] > 4, "a"] = 0` |
| Fill several columns of `df` | `df[["a", "c"]].fillna(0, inplace=True)` | `df[["a", "c"]] = df[["a", "c"]].fillna(0)` |
| Reorder `df` itself | `df.iloc[:].sort_values("b", inplace=True)` | `df = df.sort_values("b")` |
The pattern in the right-hand column is the same each time. Either assign a computed result back to the exact place you want to change, or call the in-place method on df itself.
A decision flow
When you see inplace=True in code, ask which object receives the change and whether that object is the one you care about.
The two bottom branches end in the same state: df is not updated. They differ only in whether pandas warns you.
Why the rule is better than the old behavior
It may seem like a step back that df["a"].fillna(0, inplace=True) no longer works. Before pandas 3, whether it worked depended on the internal layout of the DataFrame. If all columns shared one block of memory, df["a"] might be a view, and the call might change df. If the column had been created in a different way, df["a"] might be a copy, and the call did nothing. The same line of code gave different answers depending on how the DataFrame was built.
Under Copy-on-Write you can predict the result by reading the code. You do not need to know how df was created. The rule is that df["a"] is always an independent object, and that rule holds for every DataFrame.
Checking your own code
You can find most affected code by searching for these patterns:
- A call with
inplace=Truewhere the receiver is a subscript, such asdf["a"].something(..., inplace=True)ordf[mask].something(..., inplace=True). - A variable assigned from a column or subset, followed by an in-place call on that variable, where the code later reads the parent.
- An assignment whose right-hand side contains
inplace=True.
For the second pattern, check whether the code expects the parent to change. If a variable like col is only used as a scratch value, nothing needs to change. If the code reads df afterwards and expects an update, rewrite it with an assignment back to df.
To make the warnings visible during a test run, turn them into errors. This stops the run at the first chained operation so you can find it:
import warnings
import pandas as pd
warnings.simplefilter("error", pd.errors.ChainedAssignmentError)Put this at the top of a test module or a conftest.py. After the fixes, remove it, or keep it as a guard against new chained calls.
Does `inplace=True` still save memory?
Many people used inplace=True believing it avoided a copy. That was never reliably true, because many in-place operations built a new array internally and swapped it in. Under Copy-on-Write the difference is smaller still.
A non-in-place method such as df.fillna({"a": 0}) returns a new DataFrame. That DataFrame shares the memory of every column that was not changed. Only column a needs new data. You pay for what you modify and nothing else.
So the choice between inplace=True and assigning back is mostly about readability and about which object changes. It is not about memory. The related chapter on performance and memory covers the numbers.
Summary of the rules
- An in-place method changes only the object it is called on.
df["a"],df[mask],df[["a", "b"]]and slices are all derived objects, so an in-place call on them never changesdf.- A temporary derived object triggers
ChainedAssignmentError. A named one does not. - To change
df, call the method ondf, assign the result back, or use one.loccall. - In-place methods return
None, so never assign their result.
Exercise
The code below is meant to replace every 0 in column "score" with the column's mean of the non-zero values, and then print the "score" column. It runs without an error but prints the original values. Explain why, and rewrite the last two lines so that df is actually updated.
import pandas as pd
df = pd.DataFrame({"score": [0.0, 4.0, 0.0, 8.0]})
s = df["score"]
s.replace(0.0, 6.0, inplace=True)
print(df["score"].tolist())
Show answer
s = df["score"] creates a derived Series. Under Copy-on-Write, s is independent of df, so the in-place replace changes only s. Because s is a named variable, pandas gives no warning, and df keeps [0.0, 4.0, 0.0, 8.0]. To update df, assign the result back: df["score"] = df["score"].replace(0.0, 6.0). Calling df.replace({"score": {0.0: 6.0}}, inplace=True) also works, because the method is called on df itself. Either way print(df["score"].tolist()) shows [6.0, 4.0, 6.0, 8.0].
Exercise
A colleague wrote df["a"] = df["a"].fillna(0, inplace=True) and says the column now contains only None. Why does that happen, and what are two correct ways to write it?
Show answer
With inplace=True, fillna returns None, so the right-hand side is None, and assigning it fills the whole column with None. Two correct versions are df["a"] = df["a"].fillna(0) and df.fillna({"a": 0}, inplace=True). The first assigns a returned value. The second calls the in-place method on df and assigns nothing.
Exercise
You run subset = df[df["v"] > 1] and then subset.sort_values("v", inplace=True). Does the row order of df change? Does pandas emit a ChainedAssignmentError? Give the reason for each answer.
Show answer
The row order of df does not change, because subset is a derived object and independent of df. No ChainedAssignmentError is emitted, because subset is a named variable and not an unreferenced temporary. The warning appears only for chained expressions such as df[df["v"] > 1].sort_values("v", inplace=True), where the modified object is discarded immediately.