Sub topic 3
Interpolating Ordered Data
Assume you know basic pandas, groupby, and NumPy missing values. This chapter focuses on choosing safe repairs rather than applying one method everywhere.
Interpolating ordered data
Interpolation estimates missing values from nearby known values. It is useful for measurements recorded over an ordered index, such as time. It is unsafe for unordered categories.
import numpy as np
import pandas as pd
s = pd.Series([10.0, np.nan, np.nan, 40.0])
print(s.interpolate())The result is 10, 20, 30, 40. By default, pandas uses linear interpolation. Use ffill() when the last known value should continue, or bfill() when the next known value should apply.
Filling within groups
A single overall mean can mix different populations. groupby(...).transform(...) calculates a value per group while preserving the original row index.
df["score"] = df["score"].fillna(
df.groupby("team")["score"].transform("mean")
)Rows in groups with no observed scores remain missing. Decide explicitly how to handle them.
Nullable dtypes and `pd.NA`
Pandas nullable dtypes preserve logical types when values are missing. Int64, boolean, and string can store pd.NA.
s = pd.Series([1, pd.NA, 3], dtype="Int64")
print(s + 1)
print(s.isna())convert_dtypes() can select nullable dtypes for an existing DataFrame. This avoids silently converting an integer column to floating point.
Why the data is missing
Consider the mechanism before choosing a repair:
- MCAR: missingness is unrelated to observed or unobserved data.
- MAR: missingness depends on observed data, such as a form field skipped more often by one region.
- MNAR: missingness depends on the missing value itself, such as high earners declining to report income.
These labels describe assumptions, not automatic diagnoses.
Choosing a strategy
- Drop rows when the missing field is required and few rows are affected.
- Fill with a statistic when a representative value is defensible.
- Use
ffill,bfill, or interpolation only when order has meaning. - Use group-wise statistics when groups have different distributions.
- Record the method, affected columns, and assumptions.
Pitfalls to avoid
NaN == NaN is false, so use isna(). Aggregations usually skip missing values, but skipna=False propagates them. groupby excludes missing keys by default; use dropna=False to retain them. Assign fill results back to the column rather than relying on inplace. Check dtypes after filling, because ordinary missing values can change integer columns to floats.
Exercise
When is interpolation preferable to filling a column with its mean?
Show answer
When the rows are meaningfully ordered and nearby observed values provide a credible estimate for the gap.