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
Output:
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
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:
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:
This turns " Ana " into "Ana" and " " into missing data. For several string columns:
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
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.
Related reading
- Replacing column values in a pandas DataFrame
- Replacing Pandas or Numpy Nan with a None to use with MysqlDB
- Replicate vector in R
- Representing continuous probability distributions
- Replacing placeholder for tensorflow v2
- Representing graphs data structure in Python
- Representing the learned weights of MNIST using Tensorflow graphically
- Reproduce Fisher linear discriminant figure
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo 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 courseML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.