Sub topic 5
Extension dtypes and pd.NA
This chapter assumes you know that a column has one dtype, that NumPy dtypes like int64 are fixed-width, and that a missing value in an integer column turns it into float64. Here you will see how pandas extension dtypes avoid that promotion and what pd.NA does.
Why extension dtypes exist
NumPy has no way to mark an integer as missing. Pandas worked around this with NaN, which only exists for floats. That is why [1, 2, None] becomes float64.
Extension dtypes are types that pandas defines itself, on top of NumPy arrays. Each one has its own array class and its own rules for missing values. The common ones are:
| Dtype | Array class | Replaces |
|---|---|---|
| `Int64`, `Int32`, `UInt8`, ... | `IntegerArray` | `int64` plus `NaN` workarounds |
| `Float64`, `Float32` | `FloatingArray` | `float64` |
| `boolean` | `BooleanArray` | `bool` or `object` with `None` |
| `string` | `StringArray` | `object` holding strings |
| `datetime64[ns, UTC]` | `DatetimeArray` | naive `datetime64[ns]` |
Extension dtype names for the nullable types start with a capital letter (Int64), except boolean and string. Lowercase int64 is always the NumPy type.
How a nullable integer is stored
A nullable integer column keeps two NumPy arrays. One holds the values. The other is a boolean mask that marks which positions are missing. The value under a masked position is ignored.
The mask costs one extra byte per value. You can see it by comparing memory:
import pandas as pd
plain = pd.Series(range(1_000_000))
nullable = plain.astype("Int64")
print(plain.memory_usage(index=False))
print(nullable.memory_usage(index=False))The first number is 8,000,000 and the second is 9,000,000. Nullable types trade a little memory for correct missing-value handling.
Creating a nullable column
import pandas as pd
s = pd.Series([1, 2, None], dtype="Int64")
print(s)
print(s.dtype)
print(s.isna().sum())The column stays integer, and the missing entry prints as <NA>. You can also convert an existing column with astype("Int64"). The conversion fails if a float column has non-integer values such as 1.5.
How pd.NA behaves
pd.NA is a single missing-value marker shared by all the nullable dtypes. It follows the rule that an unknown input usually gives an unknown output.
import pandas as pd
print(pd.NA + 1)
print(pd.NA == 1)
print(pd.NA ** 0)
print(True | pd.NA)
print(False & pd.NA)The output is <NA>, <NA>, 1, True, False. The last three cases give a known answer. Any number to the power 0 is 1. True or anything is True. False and anything is False. This is three-valued logic, the same as SQL.
The main difference from NaN is comparison. np.nan == np.nan is False, but pd.NA == pd.NA is <NA>. Always test for missing values with isna() or pd.isna().
Strings and time zones
The string dtype stores text and marks missing entries with pd.NA. It also guarantees that every non-missing entry is a string, which an object column does not. An object column can mix strings, numbers, and None.
import pandas as pd
names = pd.Series(["Ada", None, "Lin"], dtype="string")
print(names.dtype)
print(names.str.len())The lengths come back as Int64, with <NA> in the middle. Methods on nullable types return nullable types, so the missing value never turns the result into float.
Datetimes with a time zone are also an extension dtype, shown as datetime64[ns, UTC]. NumPy has no time zone support, so pandas supplies its own array.
Common errors
- Writing
dtype="int64"and expecting missing values to work. The lowercase NumPy type raises an error if the data containsNone. - Mixing
np.nanandpd.NAin the same code and assuming they compare the same way. - Using nullable types everywhere without need. They use more memory, and some operations are slower than on plain NumPy arrays.
- Relying on the default string type. In pandas 2.x, plain strings are
objectunless you ask forstring. Newer versions change this default, so check your version withpd.__version__.
Exercise
A Series is created with pd.Series([10, 20, None], dtype="Int64"). What is s.sum(), what dtype does s.isna() return, and how many bytes per value does the column use for storage?
Show answer
s.sum() is 30, because sums skip missing values by default. s.isna() returns a plain bool Series, since the answer is always known. Storage is 9 bytes per value: 8 for the int64 values array and 1 for the boolean mask.