pandas
data cleaning
NaN
Python
data preprocessing

Pandas: replace empty strings and whitespace with NaN

Codemia Knowledge Hub ·

Use a regex replace: df.replace(r"^\s*$", np.nan, regex=True) turns empty strings and whitespace-only cells into NaN. After that, pandas treats them as missing values in filtering, aggregation, and type conversion.

Replacing empty and whitespace-only strings

python
1import numpy as np
2import pandas as pd
3
4df = pd.DataFrame({
5    "name": ["Ana", "  ", "", "Ben"],
6    "city": ["Paris", "Rome", "   ", "Berlin"],
7})
8
9cleaned = df.replace(r"^\s*$", np.nan, regex=True)
10print(cleaned)

Output:

text
1  name    city
20  Ana   Paris
31  NaN    Rome
42  NaN     NaN
53  Ben  Berlin

The pattern ^\s*$ matches:

  • an empty string
  • a string made only of spaces
  • a string made only of tabs or other whitespace

Why replace("", np.nan) is not enough

python
df = df.replace("", np.nan)

This only handles truly empty strings, not cells holding " " or "\t". Messy CSV and spreadsheet exports often contain whitespace rather than empty strings, which is why the regex version is more robust.

Cleaning specific columns only

To keep the cleanup scope explicit, for example when other columns hold structured values, target just the text columns:

python
text_columns = ["name", "city"]
df[text_columns] = df[text_columns].replace(r"^\s*$", np.nan, regex=True)

Stripping outer spaces from real text first

Whitespace-only cells and real text with stray outer spaces are different problems. To keep the text but trim it, strip first:

python
df["name"] = df["name"].str.strip()
df["name"] = df["name"].replace("", np.nan)

This turns " Ana " into "Ana" and " " into missing data. For several string columns:

python
1text_columns = ["name", "city"]
2
3for col in text_columns:
4    df[col] = df[col].str.strip().replace("", np.nan)

This is the better approach when the real task is both normalization and missing-value cleanup.

np.nan vs pd.NA

Both represent missing data, but they behave a little differently depending on dtype. If you rely heavily on pandas extension dtypes, pd.NA may fit better. For general cleanup, np.nan is common and works fine in many workflows. What matters is consistency: once blanks are missing values, isna(), dropna(), and type conversion become much easier to reason about.

Finding the rows that had blanks

python
missing_rows = cleaned[cleaned["name"].isna() | cleaned["city"].isna()]
print(missing_rows)

Blank strings do not take part in pandas missing-value tools, but NaN does.

Mistakes to watch for

  • Replacing only "" and missing strings that contain spaces or tabs.
  • Applying string cleanup to non-string columns without checking their dtype first.
  • Confusing trimming real text with marking whitespace-only cells as missing.
  • Being surprised when numeric conversion behaves differently afterwards. Missing values affect dtype decisions.
  • Cleaning a copy of the DataFrame and continuing to analyze the uncleaned original.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design