Sub topic 3
Turning placeholders into missing values
This chapter assumes you can create a DataFrame, select columns, and know that np.nan is NumPy's "not a number" marker. The previous chapter showed how to find missing values with isna. That only works if pandas already knows which cells are missing. Real files often use a placeholder instead, such as -999, ? or unknown. pandas reads these as ordinary data, so isna skips them and your statistics come out wrong.
Why placeholders are a problem
A placeholder, also called a sentinel value, is a normal-looking value that a data source uses to mean "no data". Suppose a sensor writes -999 when it fails. If you load that as a number, the mean of the column is dragged far below the real values, and nothing warns you.
The fix is to convert placeholders to NaN as early as possible. You can do it while loading, or afterwards with replace.
Converting while loading
read_csv already treats some strings as missing by default, including empty fields, NA, NaN, null and n/a. Use na_values to add your own markers to that list.
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 shows NaN in rows 2 and 3, and the count is 2. The row with n/a was converted by the default list. The -999 row was converted because you added it. The score column is now float64, because NaN is a float. This type change is expected, and a later chapter on nullable dtypes shows how to avoid it.
You can restrict a placeholder to one column by passing a dictionary:
from io import StringIO
import pandas as pd
csv = "id,score\n-999,10\n2,-999\n"
df = pd.read_csv(StringIO(csv), na_values={"score": [-999]})
print(df)Here -999 in id stays as data, and only score is cleaned. Per-column rules matter when the same number is legitimate in one column and a placeholder in another.
Converting after loading
If the data is already in memory, use replace. Pass the placeholder and np.nan.
import numpy as np
import pandas as pd
df = pd.DataFrame({"id": [1, 2, 3], "score": [10, -999, 30]})
df["score"] = df["score"].replace(-999, np.nan)
print(df["score"].isna().sum())
print(df["score"].mean())The count is 1 and the mean is 20.0, the average of 10 and 30. Without the replacement the mean would be about -319.7.
You can replace several placeholders in one call by passing a list: df.replace([-999, -1], np.nan). A dictionary maps columns to placeholders: df.replace({"score": -999}) needs a value too, so write df.replace({"score": {-999: np.nan}}).
Common errors
- Matching the wrong type. A column read as text holds the string
"-999", not the number.replace(-999, np.nan)then changes nothing. Checkdf.dtypesfirst, or convert the column withpd.to_numeric. - Hidden whitespace. A cell containing
" n/a"with a leading space does not matchn/a. Either list the exact string inna_valuesor strip the text first with.str.strip(). - Replacing too widely. A bare
df.replace(0, np.nan)converts every zero in every column, including valid zeros. Limit the call to the columns where zero means "unknown". - Forgetting the type change. Integer columns become float once they contain
NaN. A column that held IDs or counts will print as10.0.
Exercise
A CSV has a column temp where the value -1 means the sensor failed, and a column count where -1 is a valid value. Write the read_csv argument that converts only the failed readings.
Show answer
Pass na_values={"temp": [-1]}. The dictionary limits the placeholder to the temp column, so -1 in count is kept as data.