Sub topic 5
Dropping rows and columns with dropna
This chapter assumes you can create and index a Series and DataFrame, and that you know how to find missing values with isna. Dropping is the simplest way to handle missing data. It is also the easiest to misuse, because it removes information along with the gaps.
What dropna does
DataFrame.dropna() returns a new object with some rows or columns removed. It does not change the original. By default it drops every row that contains 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"],
})
print(df.dropna())Only Ana and Cy remain, because they are the only rows with no gaps. Ben and Dee are gone even though Dee is missing only her age.
The parameters that control it
Four parameters decide what gets removed.
| Parameter | Meaning | Default |
|---|---|---|
| `axis` | `"index"` drops rows, `"columns"` drops columns | `"index"` |
| `how` | `"any"` drops if any value is missing, `"all"` only if every value is missing | `"any"` |
| `thresh` | Keep a row or column only if it has at least this many non-missing values | not set |
| `subset` | Check only these labels when deciding | all labels |
You cannot combine how and thresh in one call. Pandas raises an error if you try.
flowchart TDChoosing which columns matter
Use subset when only some columns are required. Here a row is useful only if it has an age.
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 = df.dropna(thresh=2)
no_empty_cols = df.dropna(axis="columns", how="all")
print(with_age)
print(enough)
print(no_empty_cols)with_agekeeps Ana and Cy. Dee's missingageremoves her row, but Ben's missingcitywould not have mattered on its own.enoughkeeps rows with at least two non-missing values. Ben has only a name, so he is dropped. Dee has a name and a city, so she stays.no_empty_colsdrops only columns that are entirely missing. No column here is, so all three remain.
Check what you removed
Dropping silently shrinks your data. Compare sizes before and after, so you know how much was lost.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"age": [25, np.nan, 31, np.nan],
"city": ["Oslo", None, "Rome", "Lima"],
})
cleaned = df.dropna()
dropped = len(df) - len(cleaned)
print(f"Dropped {dropped} of {len(df)} rows ({dropped / len(df):.0%})")If the share is large, or if the dropped rows differ systematically from the kept ones, your later statistics may be biased. A later chapter covers why the reason for missingness matters.
Exercise
A DataFrame has columns "id", "score" and "comment". You want to keep every row that has an id and a score, whether or not it has a comment. Which call does this?
Show answer
df.dropna(subset=["id", "score"]). A bare df.dropna() would also drop rows where only "comment" is missing, and how="all" would keep rows that are missing both id and score as long as comment is present.