Sub topic 2
Dropping Rows and Columns with `dropna`
Assume you know how to create and index pandas DataFrames and understand np.nan. This chapter focuses on choosing whether to remove missing data or replace it.
Dropping rows and columns with `dropna`
dropna removes rows or columns containing missing values. By default, it removes every row with at least one missing value.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cy", "Dee"],
"age": [25, np.nan, 31, np.nan],
"city": ["Oslo", None, "Rome", "Lima"],
})
with_age = df.dropna(subset=["age"])
enough_data = df.dropna(thresh=2)
nonempty_columns = df.dropna(axis="columns", how="all")
print(with_age)
print(enough_data)
print(nonempty_columns)Use subset when a column is required for your analysis. Use thresh when a row must contain a minimum number of non-missing values. Set axis="columns" to remove columns instead of rows. With how="all", pandas removes a column only when every value is missing.
dropna returns a new object. Assign the result when you want to keep the change.
Filling with constants and statistics
Use fillna when you need to preserve rows. A constant can make the missing state explicit, while a statistic can provide a reasonable estimate.
df["age"] = df["age"].fillna(df["age"].median())
df["city"] = df["city"].fillna("unknown")The median is often safer than the mean when numeric data contains outliers. Calculate statistics from the training data only when building a predictive model, so information from the test data does not leak into the model.
Forward and backward fill
Forward fill, ffill, copies the last known value forward. Backward fill, bfill, copies the next known value backward. These methods suit ordered data such as time series, where nearby observations are meaningful.
s = pd.Series([1.0, np.nan, np.nan, 4.0, np.nan])
print(s.ffill())
print(s.bfill())A fill can cross a meaningful boundary, such as a new customer or sensor. Group the data first when values must remain within groups.
flowchart TD
A[Missing values] --> B{Can rows be removed?}
B -->|Yes| C[dropna]
B -->|No| D{Is order meaningful?}
D -->|No| E[fillna with a constant or statistic]
D -->|Yes| F[ffill, bfill, or interpolation]caption: Choosing a basic missing-data operation alt: A decision flow from missing values to dropping, constant filling, or ordered filling
Exercise
Which operation removes rows unless their age value is present?
Show answer
df.dropna(subset=["age"])