Sub topic 10
Nullable dtypes and pd.NA
This chapter assumes you can create a Series and DataFrame, and that you know np.nan is a float. You should also know how isna finds missing values. Here you will see why NaN can change your column types, and how nullable dtypes avoid that.
Why the default dtypes cause trouble
NumPy integer and boolean arrays have no slot for "missing". When pandas meets a missing value in such a column, it converts the whole column to float (or to object). Integer IDs and counts become 1.0, NaN, 3.0. A boolean column with a gap becomes object, which is slow and awkward.
Nullable dtypes fix this. They store the values together with a separate mask that marks which entries are missing. The marker for a missing entry is pd.NA.
| Kind of data | Default dtype with a gap | Nullable dtype |
|---|---|---|
| Integers | `float64` | `Int64` |
| Booleans | `object` | `boolean` |
| Text | `object` | `string` |
Nullable dtype names start with a capital letter (Int64), except boolean and string. The capital distinguishes them from NumPy's int64.
Creating nullable columns
Pass the dtype when you build the data. You can also let convert_dtypes choose for you.
import pandas as pd
s = pd.Series([1, None, 3], dtype="Int64")
print(s)
print(s.isna())
df = pd.DataFrame({"n": [1, 2, None]})
print(df.dtypes)
print(df.convert_dtypes().dtypes)The plain column n is float64 because of the None. After convert_dtypes() it becomes Int64. The method looks at each column and picks the nullable type that fits its values. It converts every column, so check the result before relying on it.
How pd.NA behaves
pd.NA follows three-valued logic: the result is unknown when the answer depends on an unknown value. This differs from NaN in a few places.
import pandas as pd
s = pd.Series([1, None, 3], dtype="Int64")
print(s + 1) # NA stays NA
print(s == 1) # comparison gives <NA>, not False
print(pd.NA == pd.NA) # <NA>
print(pd.NA | True) # True, because the answer does not depend on NA
print(pd.NA & False) # False, for the same reasonTwo points to remember:
- A comparison with
pd.NAreturns<NA>, notFalse. NaN comparisons returnFalse(and!=returnsTrue). - You cannot use
pd.NAdirectly in anifstatement.bool(pd.NA)raises aTypeError, because Python cannot decide whether an unknown value is true.
Aggregations still skip missing values by default, so s.sum() gives 4. Use isna and notna for detection, as before.
Mixed markers in one column
Nullable columns accept None, np.nan and pd.NA as input, and store all of them as <NA>. The fillna, dropna and isna methods work as usual on these columns.
Common errors
- Writing
dtype="int64"and gettingValueErrororIntCastingNaNErrorwhen the data has gaps. Use"Int64". - Using
if s[1] == 3:on a nullable column. The comparison can give<NA>, which fails in a condition. Checkpd.isna(value)first. - Assuming
convert_dtypesleaves your data alone. It changes dtypes, which can change how later code behaves, such as printing and merging.
Exercise
A column count contains [4, None, 6] and loads as float64. Give one line of code that makes it an integer column that keeps the gap, and state what a comparison like df["count"] == 4 returns for the missing row.
Show answer
df["count"] = df["count"].astype("Int64"). The comparison returns <NA> for the missing row, not False.