Sub topic 8
Keeping missing values with nullable dtypes
This chapter assumes you can build a DataFrame and Series, read a CSV with pd.read_csv, and use astype and pd.to_numeric as covered earlier in this tutorial. You should also be comfortable with df.dtypes. Here you will learn how to keep missing values in a column without changing the column's type.
The problem: NaN forces floats
Classic pandas columns are backed by NumPy arrays. NumPy integers have no way to represent "missing". The only missing marker available is np.nan, which is a float. So one missing value changes the whole column:
import numpy as np
import pandas as pd
ids = pd.Series([1, 2, 3])
print(ids.dtype)
with_gap = pd.Series([1, 2, None])
print(with_gap.dtype)
print(with_gap.tolist())The first dtype is int64. The second is float64, and the list shows [1.0, 2.0, nan]. The integers became floats only because one value was absent. This causes real damage:
- IDs and counts print as
3.0instead of3. - Large integers above 2**53 lose precision when stored as floats.
- Boolean columns with a gap fall back to
object, which makes them slow and awkward.
Nullable dtypes remove this coupling between the type and the missing marker.
What nullable dtypes are
Pandas provides extension dtypes that store a separate mask of which entries are missing. Their missing marker is pd.NA. Their names start with a capital letter, which separates them from the NumPy dtypes.
| Nullable dtype | NumPy-backed equivalent | What it fixes |
|---|---|---|
| `Int8`, `Int16`, `Int32`, `Int64` | `int8` to `int64` | Integers with gaps stay integers |
| `Float32`, `Float64` | `float32`, `float64` | Distinguishes NA from a computed NaN |
| `boolean` | `bool` | Booleans with gaps stay boolean instead of `object` |
| `string` | `object` holding text | A dedicated text dtype with `pd.NA` for gaps |
The capital letters matter. "int64" and "Int64" are different dtypes, and typing the wrong one is a common bug.
qty = pd.Series([3, 5, None, 7], dtype="Int64")
print(qty)
print(qty.dtype)0 3
1 5
2 <NA>
3 7
dtype: Int64The values are still integers, and the gap is shown as <NA>.
Converting to a nullable dtype
Use astype with the capitalized name. Existing NaN values in a float column become pd.NA.
floats = pd.Series([1.0, 2.0, np.nan])
as_int = floats.astype("Int64")
print(as_int.tolist())
print(as_int.dtype)This prints [1, 2, <NA>] and then Int64.
The plain NumPy conversion fails on the same input, because a NumPy integer cannot hold NaN:
try:
floats.astype("int64")
except ValueError as err:
print(type(err).__name__)The error class is IntCastingNaNError, a subclass of ValueError. The fix is to switch to Int64.
Converting text columns with gaps
For text that should become numbers, the usual pipeline is pd.to_numeric first, then astype. to_numeric produces float64 when gaps exist, and astype("Int64") converts that safely if every non-missing value is a whole number.
raw = pd.Series(["3", "5", None, "7"])
qty = pd.to_numeric(raw).astype("Int64")
print(qty.tolist())In pandas 2.0 and later you can skip the float step with the dtype_backend argument. It returns nullable dtypes directly:
direct = pd.to_numeric(raw, dtype_backend="numpy_nullable")
print(direct.dtype)This prints Int64. The same argument exists on pd.read_csv, which a later chapter covers.
When the cast refuses
astype("Int64") is strict about information loss. A float with a fractional part raises a TypeError instead of truncating:
try:
pd.Series([1.5, np.nan]).astype("Int64")
except TypeError as err:
print(type(err).__name__)This strictness protects you. If a column that should hold whole numbers contains 1.5, you want to know. Find the offending rows (see the previous chapter on failed conversions), decide whether to round or fix them, and convert afterward. Use .round() first if rounding is acceptable.
How pd.NA behaves
pd.NA means "a value exists but is unknown". That meaning produces different rules from np.nan.
Comparisons propagate NA
Comparing with an unknown value gives an unknown result:
s = pd.Series([1, None, 3], dtype="Int64")
print((s > 1).tolist())
print(pd.NA == pd.NA)The first line prints [False, <NA>, True]. The second prints <NA>, not True. To test for missing values, use pd.isna(x), s.isna() or s.notna(). Never write x == pd.NA.
The result of s > 1 has dtype boolean, so it also carries a gap.
NA in conditions
A single pd.NA cannot be used as a Python truth value:
try:
if pd.NA:
pass
except TypeError as err:
print(err)This prints boolean value of NA is ambiguous. The same error appears if you write if value: in a loop over a nullable column and value happens to be NA. Check pd.isna(value) first.
Three-valued logic
Logical operators follow the rules of three-valued (Kleene) logic. The result is only NA when the answer really depends on the unknown value.
print(True | pd.NA)
print(False | pd.NA)
print(False & pd.NA)
print(True & pd.NA)These print True, <NA>, False and <NA>. True | anything is always true, and False & anything is always false, so the unknown does not matter in those two cases.
Filtering with a masked comparison
When you use a boolean result as a filter, pandas treats NA entries as False. Rows where the comparison was unknown are dropped.
mask = s > 1
print(s[mask].tolist())This prints [3]. The missing row is not selected, and no error is raised. If you need those rows, select them explicitly with s.isna().
Aggregations skip NA
Sums, means and counts ignore missing values by default, as they do with NaN:
print(s.sum())
print(s.mean())
print(s.count())These print 4, 2.0 and 2. The sum stays an integer because the dtype is still integer.
Handling the gaps
The usual tools work the same way, and the dtype is preserved:
filled = s.fillna(0)
print(filled.dtype)
print(filled.tolist())
dropped = s.dropna()
print(dropped.tolist())fillna(0) returns an Int64 column holding [1, 0, 3]. With a NumPy float column you would get [1.0, 0.0, 3.0] unless you cast back.
Booleans and strings with gaps
A boolean column with a missing value normally degrades to object. The boolean dtype avoids that:
flags = pd.Series([True, None, False], dtype="boolean")
print(flags.dtype)
print(flags.isna().tolist())This prints boolean and [False, True, False]. The next chapter builds on this when it converts yes/no text.
For text, dtype="string" stores text with pd.NA as its missing marker:
names = pd.Series(["Ana", None, "Li"], dtype="string")
print(names.str.upper().tolist())This prints ['ANA', <NA>, 'LI']. The .str methods propagate NA instead of raising errors or returning NaN floats.
Gotchas
- Handing nullable columns to NumPy.
s.to_numpy()on a column with NA returns anobjectarray that containspd.NA, which most NumPy and scikit-learn functions reject. Choose the target explicitly:s.to_numpy(dtype="float64", na_value=np.nan). - NaN versus NA in Float64. Converting a float column with
astype("Float64")turns existing NaN values into NA, so they count as missing. Computing something like0/0yields NaN, which aFloat64column keeps as a different value from NA. Mixing the two surprises people. Useisna(), which treats both as missing. - Case in the dtype string.
astype("int64")raises on gaps, butastype("Int64")does not. If the error says a NaN cannot be converted to an integer, check the capitalization. - Performance and compatibility. Extension dtypes can be slower than NumPy ones for some operations, and some third-party libraries do not accept them yet. Convert at the boundary where you need them.
- Mixed pipelines. Operations between a NumPy
int64column and anInt64column returnInt64. The result is nullable even when no value is missing.
Summary of the workflow
- Run
df.dtypesand look for integer-like columns stored asfloat64, or boolean-like columns stored asobject. - Clean strings if needed, then parse with
pd.to_numeric. - Convert to
Int64,Float64,booleanorstringwithastype, or request nullable dtypes withdtype_backend="numpy_nullable". - Handle gaps with
isna,fillnaordropna. - Convert back with
to_numpy(dtype=..., na_value=...)when a downstream library needs NumPy arrays.
Exercise
You run pd.Series([10, 20, None]).astype("int64") and get an error. Write a one-line fix that keeps the missing value, and say what the printed dtype will be.
Show answer
Use the nullable dtype: pd.Series([10, 20, None]).astype("Int64"). The constructor produces float64 ([10.0, 20.0, NaN]), and astype("Int64") converts the whole numbers to integers and the NaN to <NA>. The dtype prints as Int64. The lowercase int64 fails because a NumPy integer cannot hold a missing value.
Exercise
Given s = pd.Series([5, None, 12], dtype="Int64"), what does s[s > 8].tolist() return, and how would you also keep the row with the missing value?
Show answer
It returns [12]. The comparison s > 8 gives [False, <NA>, True], and when it is used as a filter, NA counts as False, so the missing row is dropped. To keep it, combine the conditions: s[(s > 8) | s.isna()], which returns [<NA>, 12].