Use df.dropna(subset=["column_name"]) to return a new DataFrame with rows dropped wherever the specified column contains missing values (NaN, None, or pd.NA), or filter explicitly using boolean indexing (df[df["column_name"].notna()]).
Basic Example
import pandas as pd
import numpy as np
df = pd.DataFrame({
"name": ["Alice", "Bob", "Charlie", "Diana"],
"age": [28, np.nan, 34, 25],
"city": ["Lahore", "Karachi", np.nan, "Islamabad"],
})
# 1. Drop rows where 'age' is NaN (keeps Charlie even though 'city' is NaN)
clean_df = df.dropna(subset=["age"])
print(clean_df)
# 2. Drop rows where EITHER 'age' OR 'city' is NaN
strict_df = df.dropna(subset=["age", "city"])
print(strict_df)
Output (clean_df):
name age city
0 Alice 28.0 Lahore
2 Charlie 34.0 NaN
3 Diana 25.0 Islamabad
Key Details & Edge Cases
- Always pass
subsetas a list (subset=["col"]): Passing a list of one or more column names (subset=["age"]orsubset=["age", "city"]) restricts missing-value checks strictly to those columns while leavingNaNvalues in other columns untouched. Callingdf.dropna()withoutsubsetdrops a row if any column hasNaN. how="any"vs.how="all"with multiple columns:df.dropna(subset=["age", "city"], how="any")(the default) drops the row if at least one of the listed columns isNaN.df.dropna(subset=["age", "city"], how="all")drops the row only if every listed column isNaN.
- Resetting the index after dropping rows:
dropna()preserves the original row index labels (0, 2, 3), leaving gaps. Chain.reset_index(drop=True)if you need a clean0, 1, 2sequential index (df = df.dropna(subset=["age"]).reset_index(drop=True)). - Prefer reassignment over
inplace=True: Assign the result back (df = df.dropna(subset=["age"])) rather than usinginplace=True, which breaks method chaining and behaves inconsistently under Pandas’ Copy-on-Write (CoW) rules. - Empty strings (
"") or whitespace are NOT treated asNaN:dropna()only detects true missing-value sentinels (np.nan,None,pd.NA,pd.NaT). If a column contains empty strings"", convert them first viadf["col"] = df["col"].replace("", np.nan)before callingdropna().
Comparison of Methods for Dropping NaN Rows by Column
| Method | Syntax | Multi-Column Support | Chainable? | Best Used When |
|---|---|---|---|---|
df.dropna(subset=[...]) |
df.dropna(subset=["col"]) |
Yes (subset=["a", "b"]) |
Yes | Standard, idiomatic removal of rows with missing values in target columns. |
Boolean mask (.notna()) |
df[df["col"].notna()] |
Requires / ` |
` masks | With .loc[...] |
df.dropna(subset=[...], how="all") |
df.dropna(subset=["a", "b"], how="all") |
Yes | Yes | Keeping rows as long as at least one of the specified columns is populated. |
df.query("col.notna()") |
df.query("age.notna()") |
Yes ("a.notna() and b.notna()") |
Yes | Readable string-based filtering pipelines. |
You must log in or register to comment.