Sub topic 10
Nullable dtypes and pd.NA
This chapter assumes you can create and index a Series and DataFrame, and that you know isna, fillna and dropna from the earlier chapters. You should also know that np.nan is the usual missing marker. The examples target pandas 2.x.
The problem: NaN forces a type change
NaN is a floating-point value. A NumPy integer array has no spare bit pattern for "missing", so pandas has to change the column's type to hold one.
import pandas as pd
ints = pd.Series([1, 2, 3])
print(ints.dtype)
with_gap = pd.Series([1, None, 3])
print(with_gap.dtype)
flags = pd.Series([True, False, None])
print(flags.dtype)
tags = pd.Series(["a", None, "c"])
print(tags.dtype)The first Series is int64. The second becomes float64, because None turns into NaN and the integers become floats. The third becomes object, so the boolean column is no longer a real boolean column. The fourth is object, which holds None as a Python object.
These conversions are silent. A column of IDs or counts becomes 1.0, NaN, 3.0. A boolean column loses fast vectorised logic. Large integers above 2**53 can lose precision as floats.
Nullable dtypes fix this. They store the values in one array and the missing flags in a second boolean array (a mask), so any type can have missing entries. The missing marker is pd.NA.
The nullable dtypes
Nullable dtype names start with a capital letter or are lowercase words that are not NumPy names. That makes them easy to tell apart from the NumPy dtypes.
| Kind of data | NumPy-backed dtype | Nullable dtype | Missing marker |
|---|---|---|---|
| Integers | `int64` (no gaps allowed) | `Int8`, `Int16`, `Int32`, `Int64`, and `UInt` variants | `pd.NA` |
| Floats | `float64` | `Float32`, `Float64` | `pd.NA` |
| Booleans | `bool` (no gaps allowed) | `boolean` | `pd.NA` |
| Text | `object` | `string` | `pd.NA` |
You can request a nullable dtype when you build data:
import pandas as pd
s = pd.Series([1, None, 3], dtype="Int64")
print(s)
print(s.isna())
b = pd.Series([True, None, False], dtype="boolean")
print(b.dtype)
t = pd.Series(["a", None, "c"], dtype="string")
print(t.str.upper())
print(t.str.len())The first print shows the integers 1 and 3 with <NA> in the middle, and dtype: Int64. t.str.len() returns an Int64 Series with <NA>. On an object column the same call returns float64 with NaN.
isna, notna, dropna, fillna and the other tools from earlier chapters work on these dtypes without change. s.fillna(0) keeps the dtype as Int64. With NumPy-backed data you would get floats.
How pd.NA behaves
pd.NA means "a value exists but is unknown". Because it is unknown, most operations on it return NA instead of guessing. This differs from NaN in two ways: comparisons return NA instead of False, and using it in an if statement raises an error.
import pandas as pd
print(pd.NA + 1)
print(pd.NA == 1)
print(pd.NA == pd.NA)
try:
if pd.NA:
print("yes")
except TypeError as err:
print("TypeError:", err)The three prints give <NA>. The if raises TypeError: boolean value of NA is ambiguous. With NaN, np.nan == np.nan gives False, which hides the problem. pd.NA makes you handle it.
Three-valued logic
Boolean operations follow Kleene logic. If the known operand decides the answer whatever the unknown value is, the result is known.
import pandas as pd
print(True | pd.NA)
print(False | pd.NA)
print(False & pd.NA)
print(True & pd.NA)
print(pd.NA ** 0)
print(1 ** pd.NA)The results are True, <NA>, False, <NA>, 1 and 1. "True or anything" is true, and "False and anything" is false. Anything to the power 0 is 1, and 1 to any power is 1. The other cases depend on the unknown value, so they stay NA.
Comparisons in a column
Comparing an Int64 column gives a boolean column that can contain NA:
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cy"],
"age": pd.array([25, None, 31], dtype="Int64"),
})
mask = df["age"] > 28
print(mask)
print(df[mask])
print(mask.sum())
print(mask.fillna(False).all())When you use a boolean mask with NA to select rows, pandas treats NA as False. Only Cy is returned. mask.sum() skips NA and gives 1. If you need an explicit rule for the unknown rows, say so with fillna:
mask.fillna(False)excludes rows with unknown age.mask.fillna(True)includes them.
Aggregations and the NA rules
Aggregations still skip missing values by default (skipna=True), and skipna=False propagates them, exactly as with NaN. The difference is the result type.
import pandas as pd
s = pd.Series([1, None, 3], dtype="Int64")
print(s.sum())
print(s.sum(skipna=False))
print(s.mean())
print(s.min())s.sum() is the integer 4. s.sum(skipna=False) is <NA>. Compare with float64 data, where the sum would be 4.0 and the propagated result nan.
Converting existing data
You rarely build a Series by hand. Three routes bring real data into nullable dtypes.
astype
astype("Int64") converts a float column that has NaN, as long as the non-missing values are whole numbers.
import numpy as np
import pandas as pd
f = pd.Series([1.0, np.nan, 3.0])
print(f.astype("Int64"))If the column contains 1.5, the cast refuses to drop the fraction and raises an error. Convert to Float64 in that case.
convert_dtypes
convert_dtypes() inspects each column and picks the best nullable dtype. Whole-number floats become Int64, object columns of strings become string, and boolean-like columns become boolean.
import pandas as pd
df = pd.DataFrame({"n": [1, 2, None]})
print(df.dtypes)
print(df.convert_dtypes().dtypes)The first line shows n as float64. After conversion it is Int64, and the missing entry is <NA>.
Be aware of what it does not do. It converts every column unless you switch options off, such as convert_integer=False. It also looks at values, so a float column that happens to hold only whole numbers becomes Int64, which may not be what you want for a measurement such as a temperature.
Reading files
For CSV files you can read straight into nullable dtypes. This avoids creating floats first. Pass a mapping for chosen columns, or use dtype_backend for everything.
from io import StringIO
import pandas as pd
csv = "id,age,member\n1,25,True\n2,,False\n3,31,\n"
plain = pd.read_csv(StringIO(csv))
print(plain.dtypes)
nullable = pd.read_csv(StringIO(csv), dtype_backend="numpy_nullable")
print(nullable.dtypes)
print(nullable)
chosen = pd.read_csv(StringIO(csv), dtype={"age": "Int64"})
print(chosen.dtypes)The plain read gives age as float64 and member as object. The nullable read gives id and age as Int64 and member as boolean. The dtype mapping changes only the column you name.
Other consequences to know
- Mixed NaN and NA input. When you build a nullable column,
np.nanandNonein the input are both stored aspd.NA. The reverse is not true: converting a nullable column back tofloat64turnsNAintoNaN. - Converting to NumPy.
s.to_numpy()on anInt64column with gaps returns anobjectarray. Ask for what you want:s.to_numpy(dtype="float64", na_value=np.nan). - Library support. Some libraries (plotting, scikit-learn, older code) expect NumPy dtypes. They may fail or convert silently when they see
pd.NA. Check at the boundary. - Speed and memory. Nullable arrays carry an extra mask, so they use slightly more memory. Some operations are slower than on plain NumPy arrays.
- Default behaviour does not change. Operations such as
pd.concatorreindexcan reintroduceNaNand floats in a NumPy column. A nullable column stays nullable only when every step supports it. Re-checkdf.dtypesafter reshaping.
Choosing between them
Use nullable dtypes when:
- an integer or boolean column must stay that type despite gaps, such as IDs, counts and flags;
- you want a clear difference between "unknown" and "not a number";
- you want
stringcolumns with consistent missing handling.
Stay with NumPy-backed dtypes when:
- you pass data to libraries that expect NumPy arrays;
- the column is a measurement where
NaNis natural and speed matters.
Summary
- NumPy dtypes cannot hold a gap in an integer or boolean column, so pandas converts them to
float64orobject. Int64,Float64,booleanandstringkeep their type and usepd.NAfor gaps.pd.NApropagates through arithmetic and comparisons, follows three-valued logic, and raises when used as anifcondition.- Get nullable dtypes with
dtype=,astype,convert_dtypes()ordtype_backend="numpy_nullable"inread_csv. - Always test with
isna(), never with== pd.NA.
Exercise
You run pd.Series([4, None, 6], dtype="Int64") and store it as s. What do s.sum() and s.sum(skipna=False) return, and how would the first result differ if s were a float64 Series built from [4, np.nan, 6]?
Show answer
s.sum() returns the integer 10, because missing values are skipped. s.sum(skipna=False) returns <NA>. For the float64 Series, the first call returns 10.0 and the second returns nan.
Exercise
A DataFrame has an Int64 column age with values [25, <NA>, 31]. Write code that selects the rows where age is above 28, and also keeps the row with unknown age. Explain why df[df["age"] > 28] alone does not do this.
Show answer
Use df[(df["age"] > 28).fillna(True)]. The comparison returns a boolean Series [False, <NA>, True]. When a mask containing NA is used for selection, pandas treats NA as False, so the unknown row is dropped. Calling fillna(True) on the mask makes that choice explicit and keeps the row.
Exercise
A CSV file has a column visits with whole numbers and some empty cells. pd.read_csv gives float64. Give two ways to load it as integers with gaps.
Show answer
Pass dtype={"visits": "Int64"} to read_csv to change only that column. Or pass dtype_backend="numpy_nullable" to convert all columns to nullable dtypes. A third option is to read normally and call df["visits"].astype("Int64"), which works because the non-missing values are whole numbers.