Sub topic 8
In-place methods on columns and other derived objects
This chapter assumes you know the Copy-on-Write rule from earlier chapters: an object derived from another pandas object never changes the original. It also assumes you are comfortable with .loc and with the inplace=True argument. Here you will see what that rule does to inplace=True and to methods like Series.update when you call them on a column or other derived object.
What "in-place" means on a derived object
An in-place method changes the object it is called on and returns None. In pandas 2.x, df["a"].fillna(0, inplace=True) often updated df, because df["a"] could be a view of the DataFrame's data. Sometimes it did not, and which one you got depended on internal details.
In pandas 3, df["a"] is a derived object. Calling an in-place method on it changes only that derived object. The original DataFrame is untouched.
import pandas as pd
df = pd.DataFrame({"a": [1.0, None, 3.0], "b": [4, 5, 6]})
df["a"].fillna(0, inplace=True) # emits a ChainedAssignmentError warning
print(df["a"].tolist()) # [1.0, nan, 3.0], df is unchangedThe call fills the missing value in a temporary Series. Nothing keeps a reference to that Series, so the result is discarded. pandas detects this pattern and warns you, as it does for chained assignment.
Fixing the pattern
You have two supported ways to write this so that df changes.
- Assign the result back to the column.
- Call the in-place method on the DataFrame itself, and name the column with a dictionary.
import pandas as pd
df = pd.DataFrame({"a": [1.0, None, 3.0], "b": [4, 5, 6]})
# Option 1: assign the result back
df["a"] = df["a"].fillna(0)
print(df["a"].tolist()) # [1.0, 0.0, 3.0]
# Option 2: in-place on the DataFrame, with a dict of column -> value
df2 = pd.DataFrame({"a": [1.0, None, 3.0], "b": [4, 5, 6]})
df2.fillna({"a": 0}, inplace=True)
print(df2["a"].tolist()) # [1.0, 0.0, 3.0]Option 1 is the usual choice. It reads clearly and works with every method that returns a new object. Option 2 is useful when you want to keep the same DataFrame object, for example because other code holds a reference to it.
Holding a reference to the derived object
The warning appears when the derived object is a temporary. If you keep it in a variable, the in-place call is allowed. It then changes only that variable's object.
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], df is unchangedThis case is easy to miss, because pandas has no warning to give. The code is valid, but it does something different from what the author probably meant. Before this chapter's rule, you might have expected df to change as well. Now it does not.
Which derived objects are affected
Any object produced by indexing or by a method is derived. In-place changes on any of them stay local.
| Expression | Derived object | Does an in-place call change `df`? |
|---|---|---|
| `df["a"]` | Series | No |
| `df[["a", "b"]]` | DataFrame | No |
| `df[df["b"] > 4]` | DataFrame (filtered rows) | No |
| `df.loc[:, "a"]` | Series | No |
| `df.reset_index(drop=True)` | DataFrame | No |
| `df` itself | The original | Yes |
So df[df["b"] > 4].replace(5, 50, inplace=True) changes a temporary filtered copy and leaves df as it was.
Methods that look different but follow the same rule
Some methods change an object without an inplace argument. Series.update is one. It aligns on the index and overwrites values in place.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
fixes = pd.Series([20, 30], index=[1, 2])
df["a"].update(fixes) # modifies a temporary, warns, df is unchanged
print(df["a"].tolist()) # [1, 2, 3]
df.loc[fixes.index, "a"] = fixes # writes to df itself
print(df["a"].tolist()) # [1, 20, 30]The general fix is the same: write to df through a single .loc call, or assign a new object to the column. The earlier chapter on chained assignment covers the .loc form in more detail.
Deciding what to write
Common errors
- Writing
df["a"].method(inplace=True)and expectingdfto change. It does not, and pandas warns withChainedAssignmentError. - Filtering first and then changing the result, as in
df[mask].method(inplace=True). The filtered DataFrame is a separate object. - Storing a column in a variable and calling an in-place method on it. No warning is raised, and
dfstays the same. - Ignoring the warning during migration. Treat each
ChainedAssignmentErroras a place where the code no longer does what it did before.
Exercise
The code below runs without errors in pandas 3, but df["score"] still contains the missing value afterward. Explain why, and rewrite the last two lines so that df is updated.
import pandas as pd
df = pd.DataFrame({"score": [10.0, None, 30.0]})
s = df["score"]
s.fillna(0, inplace=True)
Show answer
s = df["score"] makes a derived Series. Under Copy-on-Write, the in-place fillna changes only s, so df keeps its missing value. No warning appears because s holds a reference. To update df, write df["score"] = df["score"].fillna(0), or use df.fillna({"score": 0}, inplace=True).