@MZeeshanM to PythonEnglish • 7 days ago

How do you drop rows in a Pandas DataFrame where a specific column has NaN?

message-square
0
1
How do you drop rows in a Pandas DataFrame where a specific column has NaN?
@MZeeshanM to PythonEnglish • 7 days ago

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 subset as a list (subset=["col"]): Passing a list of one or more column names (subset=["age"] or subset=["age", "city"]) restricts missing-value checks strictly to those columns while leaving NaN values in other columns untouched. Calling df.dropna() without subset drops a row if any column has NaN.
  • 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 is NaN.
    • df.dropna(subset=["age", "city"], how="all") drops the row only if every listed column is NaN.
  • 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 clean 0, 1, 2 sequential 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 using inplace=True, which breaks method chaining and behaves inconsistently under Pandas’ Copy-on-Write (CoW) rules.
  • Empty strings ("") or whitespace are NOT treated as NaN: dropna() only detects true missing-value sentinels (np.nan, None, pd.NA, pd.NaT). If a column contains empty strings "", convert them first via df["col"] = df["col"].replace("", np.nan) before calling dropna().

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.