Sub topic 5
Dropping rows and columns with dropna
Dropping is the simplest way to deal with missing data: you remove the rows or columns that contain it. It is also the easiest way to lose information without noticing. This chapter covers every parameter of DataFrame.dropna and the checks to run before you use it.
This chapter assumes you can build and index a Series and DataFrame, and that you know np.nan exists. It also assumes you can detect missing values with isna, covered earlier in this tutorial.
What dropna does by default
dropna returns a new object with the missing data removed. It treats NaN, None, NaT and pd.NA as missing. Called with no arguments, it drops every row that has at least one missing value in any column.
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"],
})
clean = df.dropna()
print(clean)
print(len(df), "->", len(clean))Only rows 0 and 2 survive. Ben is missing both age and city, and Dee is missing age. The original df is unchanged because dropna returns a copy by default. The surviving rows keep their original index labels (0 and 2), so the index now has a gap.
Two details are easy to forget:
- Only real missing markers count. An empty string
"", the text"N/A"and a placeholder such as-999are ordinary values, sodropnakeeps them. Convert them to missing values first, as described in the chapter on placeholders. - A Series has its own
dropna(), which removes the missing entries and takes noaxisorsubsetarguments.
The parameters at a glance
| Parameter | Default | Meaning |
|---|---|---|
| `axis` | `0` (rows) | `0` or `"index"` drops rows. `1` or `"columns"` drops columns. |
| `how` | `"any"` | `"any"` drops if at least one value is missing. `"all"` drops only if every value is missing. |
| `thresh` | not set | Keep a row or column only if it has at least this many non-missing values. |
| `subset` | not set | Check only these labels when deciding what to drop. |
| `ignore_index` | `False` | If `True`, relabel the result 0, 1, 2, and so on. |
| `inplace` | `False` | Modify the object itself. Avoid it (see the pitfalls below). |
Choosing which columns count with subset
The default rule is too strict for most real tables. A missing city should not discard a row if you only need age. The subset parameter limits the check to the columns you name.
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"])
with_city = df.dropna(subset=["city"])
with_both = df.dropna(subset=["age", "city"])
print(with_age.index.tolist()) # [0, 2]
print(with_city.index.tolist()) # [0, 2, 3]
print(with_both.index.tolist()) # [0, 2]With several columns in subset, how still applies. how="any" requires all the listed columns to be present. how="all" drops a row only when all the listed columns are missing.
Name the columns your next step needs. If you are about to compute average age per city, subset=["age", "city"] states that requirement explicitly. A bare dropna() also removes rows because of columns you never use.
Controlling strictness with how and thresh
how="all" is the lenient setting. It removes only rows that carry no information at all.
thresh is a minimum count of non-missing values. It sits between "any" and "all".
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.notna().sum(axis=1).tolist()) # [3, 1, 3, 2]
print(df.dropna(thresh=2).index.tolist()) # [0, 2, 3]
print(df.dropna(thresh=3).index.tolist()) # [0, 2]Row 1 (Ben) has only one non-missing value, so thresh=2 removes it. Dee has two, so she stays.
thresh counts the values that are present. People often read it the other way round, as a limit on missing values. If a frame has 10 columns and you want to allow at most 2 missing values per row, the right setting is thresh=8.
You cannot combine how and thresh. Passing both raises a TypeError, because each defines the rule in its own way.
When thresh is used together with subset, the count is taken only over the subset columns.
Dropping columns with axis
Set axis="columns" to drop columns instead of rows. The meaning of how and thresh carries over, but now they apply down each column.
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"],
"notes": [np.nan, np.nan, np.nan, np.nan],
})
print(df.dropna(axis="columns").columns.tolist())
# ['name']
print(df.dropna(axis="columns", how="all").columns.tolist())
# ['name', 'age', 'city']
print(df.dropna(axis="columns", thresh=3).columns.tolist())
# ['name', 'city']Dropping any column with a single missing value is rarely what you want. You would lose age and city here for having a few gaps. The common cleanup is how="all", which removes columns that are completely empty, such as the notes column above. thresh is a middle option. It keeps columns with enough data and discards sparse ones.
When axis="columns", subset lists row labels instead of column labels. It then means "decide which columns to drop by looking only at these rows". This is uncommon, but it explains why the subset argument can behave unexpectedly if you change the axis.
Tidying the index
After dropping rows, the index has gaps. Label-based lookups such as .loc[1] then fail with a KeyError, while position-based lookups still work. To get a fresh 0..n-1 index, pass ignore_index=True (available since pandas 1.4) or call reset_index(drop=True).
import numpy as np
import pandas as pd
df = pd.DataFrame({"x": [1.0, np.nan, 3.0, np.nan, 5.0]})
print(df.dropna().index.tolist()) # [0, 2, 4]
print(df.dropna(ignore_index=True).index.tolist()) # [0, 1, 2]Do not reset the index if it carries meaning, such as an ID or a timestamp. In that case the original labels tell you which records were kept.
Dropping is a filter you can write by hand
dropna is shorthand for a boolean mask. These two lines give the same result:
kept_a = df.dropna(subset=["age"])
kept_b = df[df["age"].notna()]Writing the mask by hand is useful when the rule is more specific than dropna supports. For example, you can drop rows where age is missing only for a certain group. It also lets you inspect the rows you are about to lose:
lost = df[df["age"].isna()]Looking at lost before you drop anything is a good habit. It shows whether the missing rows look random or are concentrated in one group.
Measuring what you lose
Every dropped row is data you paid to collect. Check the size of the loss before you commit.
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"],
})
before = len(df)
after = len(df.dropna(subset=["age"]))
print(f"dropped {before - after} of {before} rows ({(before - after) / before:.0%})")
print(df.isna().mean()) # share of missing values per columnThis prints dropped 2 of 4 rows (50%) and the fraction missing in each column. Half the table would disappear here, so dropping is probably the wrong choice for this data.
Small losses can still do harm. If the missing values are concentrated in one group, dropping them skews every later statistic. For example, you might drop all the rows for one region because its sensor failed. Later chapters explain why the cause of the gaps matters.
Common errors
- Using
inplace=True. It does not save memory in most cases, and it returnsNone. Code such asdf = df.dropna(inplace=True)setsdftoNone. Assign the result instead:df = df.dropna(). - Combining
howandthresh. This raises aTypeError. Pick one. - Misreading
thresh. It is a count of values to keep, not a count of missing values to allow. - Dropping before cleaning placeholders. If
-999or"n/a"is still in the data,dropnaignores it and the bad values stay in your analysis. Convert placeholders to missing values first. - Dropping on the whole frame. A bare
dropna()removes rows for gaps in columns you never use. Usesubsetinstead. - Not checking the result. An empty frame, or a much smaller one than expected, often means a mostly empty column made the default
how="any"drop nearly every row. Check withdf.isna().mean()first. - Chained assignment on a slice. If you modify the result of
df.dropna()and see aSettingWithCopyWarning, call.copy()on the result and work on that.
When dropping is reasonable
Dropping is a sound choice in these cases:
- The missing rows are few (a rough guide is a few percent) and there is no sign they differ from the rest.
- The column with gaps is the target you need, such as a label for training, and you cannot invent it.
- A column is entirely or almost entirely empty, so it holds no usable information.
- A downstream step cannot accept missing values, and filling them would be guesswork.
If none of these apply, consider filling instead, which the next chapters cover. Whichever you choose, record the decision, and record how many rows it removed.
Exercise
A DataFrame df has 10 columns. You want to keep every row that has at most 2 missing values, and you want to ignore the old index labels. Which call does this, and why does df.dropna(how="any", thresh=8) fail?
Show answer
Use df.dropna(thresh=8, ignore_index=True). A row with at most 2 missing values has at least 8 non-missing values out of 10, and thresh counts non-missing values. how and thresh cannot be passed together, so the second call raises a TypeError.
Exercise
Given df = pd.DataFrame({"a": [1, np.nan, 3], "b": [np.nan, np.nan, np.nan], "c": ["x", "y", None]}), write one call that removes only the empty column, and one call that keeps only rows where a is present. What does each return as column and index labels?
Show answer
df.dropna(axis="columns", how="all") removes b and keeps columns a and c, with index 0, 1, 2. df.dropna(subset=["a"]) keeps rows 0 and 2, drops row 1, and keeps all three columns, including the empty b.