Filling Missing Values
Replace NaN with a constant, column mean, forward fill, or backward fill using fillna() and its method parameter.
Filling Missing Values is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Introduction to fillna()
Imputation means replacing missing values with a reasonable substitute rather than dropping the row. Pandas fillna() is the primary tool for this: it replaces every NaN in a Series or DataFrame with a value you specify. Unlike dropping, imputation preserves all rows, which is especially important when data is scarce or when the missing-data pattern is informative.
The simplest form passes a scalar: df['col'].fillna(0).
import pandas as pd
import numpy as np
df = pd.DataFrame({
'product': ['A', 'B', 'C', 'D'],
'price': [10.0, np.nan, 30.0, np.nan]
})
# Fill all NaN in 'price' with 0
filled = df['price'].fillna(0)
print(filled)
# 0 10.0
# 1 0.0
# 2 30.0
# 3 0.0Filling with a Column Mean or Median
Filling with the column mean (for symmetric distributions) or median (for skewed distributions) is one of the most common imputation strategies. These statistics represent the central tendency of the data, so they minimise the distortion of the column's distribution. Always compute the statistic on the training split to avoid data leakage.
import pandas as pd
import numpy as np
df = pd.DataFrame({
'salary': [50000, np.nan, 70000, 80000, np.nan, 60000]
})
mean_salary = df['salary'].mean()
median_salary = df['salary'].median()
df['salary_mean_filled'] = df['salary'].fillna(mean_salary)
df['salary_median_filled'] = df['salary'].fillna(median_salary)
print(df)
# salary salary_mean_filled salary_median_filled
# 0 50000.0 50000.0 50000.0
# 1 NaN 65000.0 65000.0
# 2 70000.0 70000.0 70000.0Filling Categoricals with Mode
For categorical columns, filling with the mean or median doesn't make sense. Instead, use the mode — the most frequently occurring value. Series.mode()[0] returns the most common value (the [0] handles the case where there are multiple modes).
import pandas as pd
import numpy as np
df = pd.DataFrame({
'status': ['active', 'inactive', None, 'active', None, 'active']
})
most_common = df['status'].mode()[0]
print('Mode:', most_common) # active
df['status'] = df['status'].fillna(most_common)
print(df['status'].tolist())
# ['active', 'inactive', 'active', 'active', 'active', 'active']Forward Fill with ffill()
Forward fill (also called last-observation-carried-forward, LOCF) propagates the last valid (non-NaN) value forward to fill subsequent NaN positions. It is ideal for time series data where a measurement stays constant until updated — for example, device status, price levels, or sensor readings that only change at specific events.
import pandas as pd
import numpy as np
price = pd.Series(
[100, np.nan, np.nan, 105, np.nan, 110],
index=pd.date_range('2024-01', periods=6, freq='ME')
)
filled = price.ffill()
print(filled)
# 2024-01-31 100.0
# 2024-02-29 100.0
# 2024-03-31 100.0
# 2024-04-30 105.0
# 2024-05-31 105.0
# 2024-06-30 110.0Backward Fill with bfill()
Backward fill (next-observation-carried-backward, NOCB) propagates the next valid value backward to fill preceding NaN positions. This is useful when you know future data fills in missing past values — for example, if you receive end-of-month data and need to back-fill days in that month before the report arrives.
import pandas as pd
import numpy as np
df = pd.DataFrame({'value': [np.nan, np.nan, 3, np.nan, 5]})
print(df['value'].bfill())
# 0 3.0
# 1 3.0
# 2 3.0
# 3 5.0
# 4 5.0
# dtype: float64limit Parameter for Forward and Backward Fill
Both ffill() and bfill() accept a limit parameter that restricts how many consecutive NaN values are filled. This is important when you want to carry a value forward only for a short gap — long gaps should remain NaN to signal that the data is genuinely missing, not just delayed.
import pandas as pd
import numpy as np
s = pd.Series([1.0, np.nan, np.nan, np.nan, 5.0])
# Fill only the first NaN gap, leave the rest
print(s.ffill(limit=1))
# 0 1.0
# 1 1.0 <- filled
# 2 NaN <- still NaN (limit reached)
# 3 NaN
# 4 5.0Filling Different Columns Differently
In a real DataFrame, different columns may need different fill strategies. Pass a dictionary to fillna() where keys are column names and values are the fill values. This applies column-specific imputation in a single call, which is cleaner than chaining multiple individual fillna calls.
import pandas as pd
import numpy as np
df = pd.DataFrame({
'age': [25, np.nan, 30],
'income': [50000, np.nan, 70000],
'country': ['USA', np.nan, 'UK']
})
fill_values = {
'age': df['age'].median(),
'income': df['income'].mean(),
'country': 'Unknown'
}
filled = df.fillna(fill_values)
print(filled)
# age income country
# 0 25.0 50000.0 USA
# 1 27.5 60000.0 Unknown
# 2 30.0 70000.0 UKGroup-Aware Imputation
A more sophisticated strategy is to fill NaN values with the group mean or median rather than the overall column mean. For example, fill a missing salary with the median salary for that job category. This preserves subgroup structure and produces more realistic imputations than a global statistic.
import pandas as pd
import numpy as np
df = pd.DataFrame({
'dept': ['Eng', 'Eng', 'HR', 'HR', 'Eng'],
'salary': [90000, np.nan, 50000, np.nan, 110000]
})
# Fill salary NaN with the median salary for each department
df['salary'] = df.groupby('dept')['salary'].transform(
lambda x: x.fillna(x.median())
)
print(df)
# dept salary
# 0 Eng 90000.0
# 1 Eng 100000.0 <- group median (90k+110k)/2
# 2 HR 50000.0
# 3 HR 50000.0
# 4 Eng 110000.0Filling with a Constant Sentinel Value
Sometimes the right imputation is a sentinel value that signals 'unknown' rather than a real measurement. For example, -1 for unknown age, 'N/A' for unknown category, or False for an unknown boolean flag. Sentinel values are valid when downstream code explicitly checks for them and treats them differently from real data.
import pandas as pd
import numpy as np
df = pd.DataFrame({
'user_id': [1, 2, 3],
'referral_source': ['email', np.nan, 'ad'],
'trial_days': [14, np.nan, 7]
})
df['referral_source'] = df['referral_source'].fillna('unknown')
df['trial_days'] = df['trial_days'].fillna(-1).astype(int)
print(df)
# user_id referral_source trial_days
# 0 1 email 14
# 1 2 unknown -1
# 2 3 ad 7Chaining fillna() in a Pipeline
Like all Pandas methods, fillna() returns a new DataFrame and integrates cleanly into a method chain. Calling .fillna() after .dropna() applies a two-step strategy: drop rows missing critical columns, then fill remaining optional NaN values with sensible defaults — all in one readable pipeline.
import pandas as pd
import numpy as np
df = pd.DataFrame({
'user_id': [1, None, 3, 4],
'score': [88, 95, np.nan, 76],
'label': ['A', 'B', None, 'D']
})
cleaned = (
df
.dropna(subset=['user_id'])
.fillna({'score': df['score'].mean(), 'label': 'Unknown'})
)
print(cleaned)
# user_id score label
# 0 1.0 88.0 A
# 2 3.0 86.3 Unknown
# 3 4.0 76.0 DVerifying No NaN Remains
After imputation, always verify that no NaN values remain in the columns you targeted. Call df.isna().sum() or assert that the count is zero. An unexpected non-zero count means your fillna was missing a case — perhaps a column had a dtype that prevented the fill, or you forgot a column in your dict.
import pandas as pd
import numpy as np
df = pd.DataFrame({'a': [1.0, np.nan, 3.0], 'b': [np.nan, 2.0, 3.0]})
filled = df.fillna(0)
# Verify
assert filled.isna().sum().sum() == 0, 'Some NaN remain!'
print('All NaN filled successfully')
print(filled.isna().sum())
# a 0
# b 0
# dtype: int64Quick Check
Test your understanding of filling missing values in Pandas.
Lesson Recap
In this lesson you learned: fillna(scalar) replaces all NaN with a constant, fillna(mean/median) imputes with column statistics, and ffill()/bfill() propagate adjacent values for time series. Pass a dictionary to fillna() for column-specific strategies, and use groupby().transform() for group-aware imputation. Next up we cover interpolation and when to choose advanced imputation techniques.
Frequently asked questions
Is the “Filling Missing Values” lesson free?
Yes — the full text of “Filling Missing Values” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.
What will I learn in “Filling Missing Values”?
Replace NaN with a constant, column mean, forward fill, or backward fill using fillna() and its method parameter. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Pandas & NumPy Academy?
No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Filling Missing Values” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Pandas & NumPy Academy lesson?
Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Detecting Missing Values
- Dropping Missing Values
- Filling Missing Values
- Interpolation and Advanced Imputation