Sub topic 5
Extension dtypes and pd.NA
This chapter assumes you know how NumPy dtypes work and how missing values force an integer column to float64. It also assumes you know that the object dtype stores pointers to Python objects. Those topics come from the earlier chapters. Here you will learn what pandas does when NumPy's dtypes are not enough. You will also learn how the pd.NA marker behaves, and which errors to expect when you switch a column to a nullable dtype.
Why NumPy dtypes are not enough
A NumPy integer array has no spare bit pattern that means "missing". Every possible 64-bit value is a valid integer. Floats do have such a pattern, NaN, which is why a missing value turns an integer column into float64. Text has a different problem. NumPy has no variable-length string type that pandas can use, so strings fall back to object.
Pandas solves this with extension dtypes. An extension dtype is a column type defined by pandas (or a third-party library) instead of NumPy. Two classes describe it:
ExtensionDtypedescribes the type: its name, its missing-value marker, and how to build arrays of it.ExtensionArrayholds the data and implements the operations pandas needs: indexing,take,isna, concatenation, and so on.
A Series or DataFrame column backed by an extension dtype is still a column in the sense of the first chapter. It has one dtype and shares the frame's index. Only the array behind it differs.
The extension dtypes you will meet
| Dtype name | Replaces | Missing marker | Notes |
|---|---|---|---|
| `Int8` to `Int64`, `UInt8` to `UInt64` | `int8` to `int64`, `uint8` to `uint64` | `pd.NA` | Capitalized names are the nullable versions |
| `Float32`, `Float64` | `float32`, `float64` | `pd.NA` | Distinguishes missing from a computed `NaN` |
| `boolean` | `bool` or `object` | `pd.NA` | Three-valued logic |
| `string` | `object` holding strings | `pd.NA` | Only strings (and NA) are allowed |
| `datetime64[ns, tz]` | none (NumPy has no time zones) | `NaT` | Time-zone-aware timestamps |
| `category` | `object` with repeated values | `NaN` (code -1) | Covered in its own chapter |
The capital letter is how you tell Int64 (pandas, nullable) from int64 (NumPy, not nullable). The lowercase names are NumPy dtypes. Passing dtype="Int64" selects the pandas one.
Time-zone-aware datetimes are an extension dtype that keeps NaT as its missing marker. Do not expect pd.NA in a datetime column.
How a nullable integer is stored
The nullable integer, float, and boolean dtypes use a masked array layout. Each array holds two NumPy arrays of the same length:
- a data array with the normal fixed-width values, such as
int64 - a boolean mask array where
Truemeans "this position is missing"
The value under a masked position is meaningless. Only the mask decides whether an entry is missing.
This design has two consequences:
- Fast vectorized code still runs on the contiguous data array, and no Python objects are involved.
- Each value costs one extra byte for the mask.
You can see the cost directly:
import numpy as np
import pandas as pd
n = 1_000_000
plain = pd.Series(np.arange(n))
nullable = pd.Series(np.arange(n), dtype="Int64")
print(plain.memory_usage(index=False)) # 8000000
print(nullable.memory_usage(index=False)) # 9000000A nullable Int64 column takes about 12.5% more memory than int64. That is still far less than the float64 detour for integers, and much less than object. Note that float64 takes the same 8 bytes per value as int64, so the detour costs precision and clarity rather than bytes. Large integers above 2**53 cannot be stored exactly in a float.
Creating and using a nullable column
import pandas as pd
s = pd.Series([1, 2, None], dtype="Int64")
print(s)
print(s.dtype)
print(s.isna().tolist())
print(s.sum(), s.mean())The output shows <NA> in the last position, then Int64, then [False, False, True], then 3 1.5. The values 1 and 2 remain integers. Reductions such as sum and mean skip missing values by default, the same as with NaN.
isna, notna, fillna, and dropna work the same way for every dtype. Code that only uses these methods needs no changes when you switch dtypes.
How pd.NA behaves
pd.NA is a single object that means "a value exists but is unknown". Its rules follow three-valued logic. If an unknown value could change the result, the result is unknown. If it cannot, the result is known.
import pandas as pd
print(pd.NA == 1) # <NA>
print(pd.NA == pd.NA) # <NA>
print(pd.NA + 1) # <NA>
print(pd.NA ** 0) # 1, because anything to the power 0 is 1
print(True | pd.NA) # True, because the result is True either way
print(False | pd.NA) # <NA>
print(False & pd.NA) # False, because the result is False either way
print(pd.isna(pd.NA)) # True
try:
bool(pd.NA)
except TypeError as e:
print(e) # boolean value of NA is ambiguousCompare this with NaN, where np.nan == np.nan is False and np.nan > 1 is False. NaN comparisons always give a definite answer, even though the question has none. pd.NA comparisons stay unknown.
The last case matters in practice. bool(pd.NA) raises, so if value: and value and other fail when value is pd.NA. Test with pd.isna(value) first.
Comparisons give a boolean column
Comparing a nullable column produces a boolean column that can contain <NA>:
import pandas as pd
s = pd.Series([1, 2, None], dtype="Int64")
mask = s > 1
print(mask.dtype) # boolean
print(mask.tolist()) # [False, True, <NA>]
print(s[mask].tolist()) # [2]
print(mask.fillna(False).tolist()) # [False, True, False]When a boolean mask is used to select rows, pandas treats <NA> as False. Rows with unknown results are dropped silently. That is usually what you want, but be explicit when it matters. Use fillna(False) or fillna(True) to state your choice.
A float64 column behaves differently. A comparison on NaN returns plain False, so s > 1 has a plain bool dtype and no missing entries.
Logical operators
For boolean columns, &, |, and ^ follow the same Kleene logic as the scalar examples above. False & NA is False, True | NA is True, and the other combinations with NA stay NA. Python's and, or, and not do not work elementwise on Series. Use &, |, and ~.
Converting to nullable dtypes
There are three common routes.
Set the dtype when you build the column. pd.Series([1, None], dtype="Int64") and pd.array([1, None], dtype="Int64") both work. np.nan is also accepted as a missing value in this case and becomes <NA>.
Convert with astype.
import numpy as np
import pandas as pd
print(pd.Series([1.0, np.nan]).astype("Int64").tolist()) # [1, <NA>]
try:
pd.Series([1.5, 2.0]).astype("Int64")
except TypeError as e:
print(type(e).__name__) # TypeError, the cast would lose 0.5Floats convert to Int64 only when every non-missing value is a whole number. Otherwise pandas raises instead of truncating.
Let pandas choose with convert_dtypes().
import numpy as np
import pandas as pd
df = pd.DataFrame({
"id": [1, 2, 3],
"score": [1.0, 2.0, np.nan],
"name": ["Ann", None, "Cy"],
"ok": [True, False, None],
})
print(df.dtypes)
print(df.convert_dtypes().dtypes)In pandas 2.x, the original dtypes are int64, float64, object, object. After conversion they are Int64, Int64, string, boolean. The score column becomes Int64 because all its non-missing values are whole numbers. If you want Float64 there, pass convert_integer=False.
Getting back to NumPy
Converting a column with missing values back to NumPy needs a decision about what represents "missing":
import numpy as np
import pandas as pd
s = pd.Series([1, 2, None], dtype="Int64")
print(s.to_numpy().dtype) # object
print(s.to_numpy(dtype="float64", na_value=np.nan)) # [ 1. 2. nan]Without arguments, the result is an object array that holds pd.NA. Libraries that expect numeric arrays may fail on that. Pass dtype and na_value to get what you need.
The string dtype
dtype="string" stores only strings and pd.NA. Unlike object, it rejects other Python objects:
import pandas as pd
names = pd.Series(["Ann", None, "Cy"], dtype="string")
print(names.str.len().tolist()) # [3, <NA>, 2]
print(names.str.upper().tolist()) # ['ANN', <NA>, 'CY']Methods on the .str accessor return nullable dtypes. Here str.len() returns Int64, not float64. In an object column, the same call returns float64 when any value is missing.
The default string dtype in pandas 2.x still keeps Python string objects in memory, so by itself it does not save memory. The gain is correctness and clear semantics. A variant backed by PyArrow does save memory, and a later chapter covers it. Pandas 3.0 and later infer a string dtype for text columns by default. Check your version before assuming that text loads as object.
Common errors
- Using
if x:on a missing value.bool(pd.NA)raisesTypeError. Checkpd.isna(x)first. - Assuming
==finds missing values.s == pd.NAreturns all<NA>, neverTrue. Uses.isna(). - Mixing
Int64withint64in a merge or concat and expecting the same dtype out. ConcatenatingInt64withint64givesInt64. ConcatenatingInt64withfloat64usually givesFloat64. Check.dtypesafter combining frames. - Passing a nullable column straight to code that expects NumPy. Some libraries call
np.asarrayand receive anobjectarray. Convert withto_numpy(dtype=..., na_value=...). - Forgetting the capital letter.
dtype="int64"with aNonein the data raises or silently givesfloat64.dtype="Int64"is the nullable one. - Expecting
pd.NAin datetime columns. Time-zone-aware columns useNaT. - Using private attributes in production. Names such as
_dataand_maskexist on masked arrays but may change between versions. Use the public API:to_numpy,isna, and.array.
Choosing between the options
| Situation | Choice |
|---|---|
| Integer column that may have gaps, and you need exact integers | `Int64` (or a smaller width) |
| Float column where missing and computed `NaN` must be told apart | `Float64` |
| Flag column with unknown values | `boolean` |
| Text column that must hold only strings | `string` |
| No missing values and downstream code expects NumPy | Keep `int64` or `float64` |
| Few distinct text values repeated many times | `category` |
Exercise
A Series is created with s = pd.Series([3, None, 5], dtype="Int64"). What dtype does s > 4 have, what does (s > 4).tolist() return, and what does s[s > 4].tolist() return?
Show answer
s > 4 has dtype boolean. (s > 4).tolist() returns [False, <NA>, True], because comparing pd.NA with 4 is unknown. s[s > 4].tolist() returns [5], because boolean indexing treats <NA> as False.
Exercise
Why does pd.Series([1.5, 2.0]).astype("Int64") raise a TypeError, while pd.Series([1.0, 2.0]).astype("Int64") succeeds? Name the dtype that would hold the first series without loss.
Show answer
The cast must not change any value. 1.5 is not a whole number, so converting it to an integer would lose the fraction, and pandas raises instead of truncating. 1.0 and 2.0 convert exactly. The first series can be held by Float64 (or plain float64 if it has no missing values).
Exercise
A nullable Int64 column of 2,000,000 values uses how many bytes, and why is that more than the same data in int64?
Show answer
It uses 18,000,000 bytes: 16,000,000 for the int64 data array (8 bytes per value) plus 2,000,000 for the boolean mask (1 byte per value). The plain int64 column uses only the 16,000,000 data bytes, so the nullable one costs one extra byte per value.