Sub topic 3
Turning placeholders into missing values
This chapter assumes you can create and index a Series and DataFrame, and that you know np.nan and isna from the earlier chapters. It covers placeholder values, which are real-looking entries that stand in for "no data". You will learn to convert them to proper missing values.
Why placeholders are a problem
Data rarely arrives with clean NaN values. Systems that export data often write something else for "unknown":
- Numeric codes such as
-999,-1, or9999. - Text such as
"n/a","?","unknown","NULL", or an empty string. - Blank cells made only of spaces.
pandas treats these as ordinary values. A -999 in a score column goes straight into mean() and drags the result down. An "unknown" in a city column counts as a city when you call value_counts(). A column that mixes numbers and "n/a" can load as object dtype, so numeric operations fail or behave unexpectedly.
The fix is to convert placeholders to missing values as early as possible. After that, isna, dropna, fillna and the skip-missing behaviour of aggregations all work as intended.
Two places to fix it
You can convert placeholders at load time or after loading.
| Approach | Tool | Best when |
|---|---|---|
| At load time | `na_values`, `keep_default_na`, `na_filter` in `read_csv` | The placeholder is known before you see the data, and you want correct dtypes immediately |
| After loading | `replace`, `mask`, `where`, `to_numeric(errors="coerce")` | The data comes from a database, an API, or an Excel sheet, or you discover placeholders later |
Load-time conversion is usually better. When a numeric column contains -999 and "n/a", converting both while parsing lets pandas infer a numeric dtype in one step.
Using na_values in read_csv
read_csv already treats a set of strings as missing by default. These include the empty string, "NA", "N/A", "n/a", "NaN", "nan", "NULL", "null", and a few others. The na_values argument adds more strings to that set.
from io import StringIO
import pandas as pd
csv = "id,score\n1,10\n2,-999\n3,n/a\n"
df = pd.read_csv(StringIO(csv), na_values=["-999"])
print(df)
print(df["score"].isna().sum())The output is:
id score
0 1 10.0
1 2 NaN
2 3 NaN
2Both -999 and n/a became NaN. The n/a came from the default list and the -999 from your addition. Because the column now contains NaN, its dtype is float64, so 10 is displayed as 10.0. A later chapter on nullable dtypes shows how to keep integers.
Different placeholders per column
A global list is risky. In one column, -1 may mean "unknown". In another it may be a legitimate value, and 0 may be a real count. Pass a dictionary to apply placeholders only where they belong.
from io import StringIO
import pandas as pd
csv = "name,age,qty\nAna,-1,0\nBen,41,3\nCy,29,-1\n"
df = pd.read_csv(StringIO(csv), na_values={"age": ["-1"], "qty": ["-1"]})
print(df)The output is:
name age qty
0 Ana NaN 0.0
1 Ben 41.0 3.0
2 Cy 29.0 NaNAna's quantity of 0 is kept as a real value. Only the -1 entries became missing.
When the defaults are wrong
The default list can hurt you. The country code for Namibia is NA, and read_csv will turn it into a missing value. Use keep_default_na=False to switch the built-in list off, then name the markers you want.
from io import StringIO
import pandas as pd
csv = "country,pop\nNO,5.4\nNA,2.5\nSE,\n"
default = pd.read_csv(StringIO(csv))
custom = pd.read_csv(StringIO(csv), keep_default_na=False, na_values=[""])
print(default["country"].isna().sum())
print(custom["country"].isna().sum())
print(custom["pop"].isna().sum())The output is 1, 0, and 1. With defaults on, "NA" in country is lost. With keep_default_na=False and na_values=[""], only empty fields are missing, so Namibia survives and Sweden's empty population is still detected.
The behaviour depends on how the two arguments combine:
| `keep_default_na` | `na_values` given | Result |
|---|---|---|
| `True` (default) | no | Only the default markers are missing |
| `True` | yes | Default markers plus your list |
| `False` | yes | Only your list |
| `False` | no | Nothing is missing, and every cell stays as text or a number |
A related argument, na_filter=False, turns off missing-value detection entirely. It can speed up loading of big files that you know have no gaps, but it leaves placeholders and empty strings in place, so use it with care.
Replacing placeholders after loading
When the data is already in memory, replace swaps a placeholder for np.nan. Whitespace-only cells are a common case, and a regular expression handles them along with other text markers.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"temp": [21.5, -999, 23.0, -999],
"status": ["ok", "?", " ", "ok"],
})
df["temp"] = df["temp"].replace(-999, np.nan)
df["status"] = df["status"].replace(r"^\s*$|^\?$", np.nan, regex=True)
print(df)
print(df.isna().sum())The pattern ^\s*$ matches empty or whitespace-only strings. The pattern ^\?$ matches a lone question mark. Both temp and status end up with two missing values.
Notice that the result is assigned back to the column. replace returns a new object and does not modify the original.
You can also pass a dictionary to replace several placeholders in one call, such as df.replace({"?": np.nan, "unknown": np.nan}). On a whole DataFrame this touches every column, so check that a string like "unknown" is never legitimate anywhere else.
Rule-based conversion with mask
Sometimes the placeholder is a range of impossible values, not one value. mask replaces values with NaN wherever a condition is true.
import pandas as pd
ages = pd.Series([34, 29, -1, 250, 41])
clean = ages.mask((ages < 0) | (ages > 120))
print(clean)The result is 34.0, 29.0, NaN, NaN, 41.0. The opposite method, where, keeps values where the condition is true and replaces the rest.
Coercing unparseable text with to_numeric
If a column is stored as text and should be numeric, pd.to_numeric(..., errors="coerce") turns anything it cannot parse into NaN. pd.to_datetime accepts the same errors="coerce" argument for dates.
import pandas as pd
raw = pd.Series(["12", "7.5", "n/a", "oops"])
clean = pd.to_numeric(raw, errors="coerce")
print(clean)
unexpected = raw[clean.isna() & ~raw.isin(["n/a"])]
print(unexpected)The first print shows 12.0, 7.5, NaN, NaN. The second shows only oops at index 3.
Coercion is convenient but blunt. It converts every failure to NaN, including typos and corrupted values that you may want to know about. The second step above guards against this. It lists the entries that became missing but were not an expected placeholder, so you can inspect them.
A workflow for finding placeholders
You can only convert placeholders you know about. Before choosing a list, look for them.
- For text columns, call
value_counts()and read the most frequent values. Placeholders tend to appear near the top. - For numeric columns, check
describe(). A minimum of-999or a maximum of9999is a strong hint. - Compare against documentation or a data dictionary, if one exists.
- Convert, then count missing values per column with
isna().sum()and compare with the count before conversion.
Edge cases and common errors
- A real value looks like a placeholder.
0can be a valid count, temperature, or balance. Converting it to missing silently removes real data. Apply zero as a placeholder only to columns where the documentation says so. - Placeholders differ in type. The text
"-999"and the number-999are different. Inread_csv,na_valuesmatches the raw text, so write it as a string. Inreplace, match the dtype of the column, using-999for a numeric column. - Extra spaces. A cell such as
" n/a"is not recognised by the default list. Strip whitespace first, useskipinitialspace=Trueinread_csv, or use the regex approach shown earlier. - Dtype changes. Integers with placeholders become
float64once converted. This is expected, and nullable dtypes are the way to keep integers. - Placeholders in the index or headers.
na_valuesapplies to data cells. If your index contains placeholders, handle them separately. - Document your conversions. Keep the list of placeholders in one named constant or in a comment so the cleaning step is reproducible.
Exercise
A CSV has columns id, age and visits. In age, the value -1 means unknown. In visits, -1 is not used, but 0 is a real count and must be kept. The country-style text NA does not appear. Write the read_csv call that loads this file with age placeholders converted, and explain why you did not use a single global na_values=["-1", "0"].
Show answer
Use pd.read_csv("file.csv", na_values={"age": ["-1"]}). The dictionary applies the placeholder to age only. A global list containing "0" would turn every real zero in visits (and in any other column) into NaN, which silently deletes valid data and biases later statistics. Giving -1 only to the column where it means "unknown" avoids this.
Exercise
A Series s = pd.Series(["5", "8", "none", "x9"]) should be numeric. "none" is a known placeholder, but "x9" is unexpected. How do you convert the Series and also list the unexpected entries?
Show answer
Run clean = pd.to_numeric(s, errors="coerce"), which gives 5.0, 8.0, NaN, NaN. Then run s[clean.isna() & ~s.isin(["none"])]. This returns only "x9", because it became missing but is not an expected placeholder. You can then decide whether to correct it, drop it, or investigate the source.