Sub topic 1
How pandas Represents Missing Values
Prerequisites
Assume you know basic Python, can create and index pandas Series and DataFrame objects, and recognize np.nan.
How pandas represents missing values
Pandas uses several markers for missing data. None is Python’s empty value. np.nan is a floating-point “not a number” value. pd.NaT represents a missing date or time. pd.NA is pandas’ general missing-value marker, used by nullable data types.
| Marker | Typical use |
|---|---|
| `np.nan` | Missing numeric value |
| `None` | Missing object or text value |
| `pd.NaT` | Missing datetime or timedelta |
| `pd.NA` | Missing value in nullable types |
The marker you see can depend on the column’s data type. Missing values can also change a column’s type. For example, a regular integer column may become floating-point when np.nan is inserted.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cy", "Dee"],
"age": [25, np.nan, 31, np.nan],
"city": ["Oslo", None, "Rome", "Lima"],
})
print(df)Finding missing values
Use isna() to return a Boolean object with True where a value is missing. Use notna() for the inverse. To count missing values in each column, chain sum():
print(df.isna())
print(df.isna().sum())
print(df["age"].notna().sum())Turning placeholders into missing values
Real files often use sentinel values, which are ordinary values that mean “missing,” such as -999, "unknown", or "n/a". Convert them while loading the data:
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())How missing values behave in calculations
Many pandas aggregations skip missing values by default:
s = pd.Series([1.0, np.nan, 3.0])
print(s.sum()) # 4.0
print(s.sum(skipna=False)) # nan
print(s == np.nan) # False, False, False
print(s.isna()) # False, True, FalseArithmetic usually propagates missing values. Aggregations such as sum() and mean() commonly skip them unless skipna=False is specified.
Exercise
How should you count missing values in a Series?
Show answer
Call series.isna().sum().