How do you fill or replace NaN values in a specific Pandas DataFrame column? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you fill or replace NaN values in a specific Pandas DataFrame column?

message-square
0

Use df["col"] = df["col"].fillna(value) (or df.fillna({"col_a": 0, "col_b": "Unknown"}) to fill multiple columns with distinct defaults in a single call) to replace NaN, None, and pd.NA values in specific Pandas columns without triggering SettingWithCopyWarning or mutating unrelated columns.

Basic Example

import numpy as np
import pandas as pd

df = pd.DataFrame({
    "category": ["Books", np.nan, "Music", None],
    "price": [15.0, 25.0, np.nan, 40.0],
    "stock": [10, np.nan, np.nan, 5],
})

# 1. Recommended (single column with constant or computed statistic):
df["category"] = df["category"].fillna("Uncategorized")
df["price"] = df["price"].fillna(df["price"].median())

# 2. Recommended (multiple columns at once via dictionary mapping):
df = df.fillna({"stock": 0})
print(df)
#         category  price  stock
# 0          Books   15.0   10.0
# 1  Uncategorized   25.0    0.0
# 2          Music   25.0    0.0
# 3  Uncategorized   40.0    5.0

Key Details & Edge Cases

  • Avoid df["col"].fillna(0, inplace=True) (broken in Pandas 2.x/3.0 Copy-on-Write):
    • Under Copy-on-Write (enabled by default in Pandas 3.0 and warned against in Pandas 2.x via FutureWarning: A value is trying to be set on a copy of a DataFrame or Series through chained assignment), df["col"].fillna(0, inplace=True) mutates a temporary Series copy and silently leaves df["col"] unchanged! Always assign back: df["col"] = df["col"].fillna(0) or df = df.fillna({"col": 0}).
  • Forward-filling and backward-filling time-series gaps (.ffill() / .bfill()):
    • In Pandas 2.0+, fillna(method="ffill") and fillna(method="bfill") are deprecated and removed in Pandas 3.0. Call df["col"] = df["col"].ffill() (propagate last valid value forward) or df["col"] = df["col"].bfill() (backfill next valid value), optionally passing limit=2 to cap consecutive filled gaps.
  • Filling missing values within groups (groupby().transform()):
    • When replacing NaN with a per-category average or median rather than a global one, combine .fillna() with .groupby(...).transform(...):
      df["price"] = df["price"].fillna(df.groupby("category")["price"].transform("median"))
      
  • Dtype compatibility trap on nullable "Int64", "string", or Categorical columns:
    • Filling an "Int64" integer column with a float (df["int_col"].fillna(0.5)) or filling a Categorical column with a label not yet registered in .cat.categories raises TypeError / ValueError. For Categorical columns, add the new category first: df["cat"] = df["cat"].cat.add_categories(["Missing"]).fillna("Missing").
  • Empty strings "" or whitespace " " are NOT treated as NaN by .fillna():
    • .fillna() only replaces true null sentinels (np.nan, None, pd.NA, pd.NaT). Convert blank strings to np.nan first if needed: df["col"] = df["col"].replace(r"^\s*$", np.nan, regex=True).fillna("Unknown").

Comparison of Missing-Value Replacement Methods in Pandas

Method Syntax Example Replaces NaN / None / pd.NA? Replaces Arbitrary Non-Null Sentinels (e.g., -1, "")? Best Used When
df["col"] = df["col"].fillna(val) (Default) df["price"] = df["price"].fillna(0) Yes No Filling missing values in a single column with a constant, mean, or median.
df = df.fillna({"col1": v1, "col2": v2}) df = df.fillna({"a": 0, "b": "N/A"}) Yes No Filling multiple columns with different default values cleanly in one step.
df["col"] = df["col"].ffill() / .bfill() df["temp"] = df["temp"].ffill(limit=3) Yes No Carrying forward or backward adjacent observations in sorted time-series data.
df["col"] = df["col"].interpolate() df["sensor"] = df["sensor"].interpolate() Yes No Estimating missing numeric values smoothly via linear or time-weighted interpolation.
df["col"] = df["col"].replace(-999, np.nan) df["age"] = df["age"].replace(-1, np.nan) Yes Yes (matches any target value/regex) Converting sentinel placeholder codes (-999, "N/A", "") into true NaNs before filling.