Python for Data Analytics & AutomationLesson 23 of 41
Lesson 23 of 41

Handling Missing Data in Pandas: isna, notna, dropna & fillna Strategies

Overview & Learning Objectives

Missing data is inevitable in real-world pipelines due to sensor dropouts, customer skipped fields, or system integration mismatches. Pandas distinguishes missing numeric data as `np.nan` (or `pd.NA` in newer nullable types) and missing strings as `None` or ``. Analytics professionals must diagnose the missingness pattern (MCAR, MAR, MNAR) and apply appropriate treatment—whether filtering, constant imputation, forward-filling for time series, or mean/median imputation.

  • Detect and count missing values across columns using `.isna().sum()` and percentage calculation.
  • Drop records or columns conditionally using `.dropna(how="any"|"all", thresh=k, subset=[...])`.
  • Impute missing values using `.fillna()` with scalar values, statistical summaries, or forward/backward propagation.

Industry Standard

Standard: Top tech data teams at Uber and DoorDash establish automated pipeline checks that alert if missing value ratios exceed 5% on critical business metrics like transaction price or delivery time.

Real-World Example: ScoopCraft Dark-Store Incomplete Order Audit

ScoopCraft quality analysts inspect order intake logs where delivery driver tips and delivery times contain missing entries.

Order_IDSubtotalTip_AmountDelivery_MinClean_Action
ORD-501$24.50NaN18.2Fill Tip with 0.0
ORD-502$18.00$3.00NaNImpute median delivery time (22.5)
ORD-503NaNNaNNaNDrop row (thresh condition)
ORD-504$32.50$5.0019.4Valid record (no action)

Functions & Methods Covered in this Chapter

Here is the definition, execution syntax, parameter breakdown, and real-world business example for each function/method covered in this chapter:

Function 1

df.isna() / df.notna()

Definition: Detects missing values (NaN, None, NaT) across DataFrames or Series, returning boolean masks of equal shape.

Syntax / Code Pattern:
missing_counts = df.isna().sum()
Real-World Example (Dark-Store Inventory Audit):
Problem / Scenario: Count missing expiry dates across SKU records.
Code / Expression: df["expiry_date"].isna().sum()
Result: 14 (Integer count of null values)
Why it works: Evaluates each cell in the expiry_date column and sums True values.
Function 2

df.fillna(value=None, method=None, inplace=False)

Definition: Fills NA/NaN values using specified constant value, dictionary of column mappings, or forward/backward fill.

Syntax / Code Pattern:
df["delivery_rating"] = df["delivery_rating"].fillna(df["delivery_rating"].median())
Parameters Breakdown:
  • value: Scalar value or dict mapping column names to imputation values.
  • inplace: Boolean. If True, modifies DataFrame in-place.
Real-World Example (Customer Tip Imputation):
Problem / Scenario: Replace null rider tip entries with 0.0 to prevent arithmetic NaN propagation.
Code / Expression: df["tip_amount"] = df["tip_amount"].fillna(0.0)
Result: All NaN cells in tip_amount column replaced with 0.0
Why it works: Ensures arithmetic revenue columns calculate accurately without dropped rows.
Function 3

df.dropna(axis=0, how="any", subset=None)

Definition: Removes missing values by dropping rows (axis=0) or columns (axis=1) meeting designated threshold criteria.

Syntax / Code Pattern:
df_cleaned = df.dropna(subset=["customer_phone", "order_total"])
Parameters Breakdown:
  • axis: 0 or "index" to drop rows, 1 or "columns" to drop columns.
  • how: "any" drops record if any NA is present, "all" drops only if all values are NA.
  • subset: List of column labels to inspect for missing values.
Real-World Example (Removing Invalid Customer Records):
Problem / Scenario: Drop orders where primary customer contact number is completely missing.
Code / Expression: df_clean = orders_df.dropna(subset=["customer_phone"])
Result: DataFrame reduced from 10,000 to 9,880 valid contactable records.
Why it works: Discards unserviceable delivery rows while preserving valid transactions.
Function 4

df.interpolate(method="linear")

Definition: Fills NaN values using mathematical interpolation techniques (linear, time, polynomial) based on surrounding points.

Syntax / Code Pattern:
sensor_df["temperature"] = sensor_df["temperature"].interpolate(method="time")
Parameters Breakdown:
  • method: Interpolation method: "linear", "time", "index", "polynomial".
Real-World Example (Ice Cream Cold-Storage Sensor Reading):
Problem / Scenario: Interpolate missing freezer temperature readings recorded every 10 minutes.
Code / Expression: df["freezer_temp_c"] = df["freezer_temp_c"].interpolate(method="linear")
Result: Smooth temperature curve without missing telemetry gaps.
Why it works: Computes midpoint values between prior and subsequent sensor timestamps.

Common Mistakes & Limitations

  • Using `df == np.nan` to check for missing values (always returns False because IEEE 754 NaN != NaN; always use `.isna()`).
  • Filling numeric columns with string `"N/A"` which coerces the entire column dtype to `object` and breaks future math.
  • Dropping rows across the entire DataFrame without specifying `subset`, inadvertently discarding valuable data due to a single irrelevant optional column.

Keyboard Shortcuts (Jupyter & VS Code)

ActionWindowsMac
Search for NaN or missing value tokens in VS CodeCtrl + FCmd + F

Pro Tips & Modern Best Practices

  • In modern Pandas (>= 2.0), use `.ffill()` and `.bfill()` directly instead of `fillna(method="ffill")`, which is deprecated.
  • Use the `missingno` library (`import missingno as msno; msno.matrix(df)`) to visualize sparsity matrices and correlated missingness visually in Jupyter.