Sub topic 4
How missing values change dtypes
This chapter assumes you can build a DataFrame, select columns, and read a column's dtype. It also assumes you know that a plain pandas column is backed by a NumPy array, as covered earlier in the tutorial. Here you will learn why a single missing entry can change the type of an entire column. You will also learn how to predict that change and how to prevent it.
Why a missing value is a type problem
A NumPy int64 array stores one 8-byte integer in every slot. Every bit pattern in those 8 bytes is a valid integer, so no pattern is left over to mean "missing".
Floating-point numbers are different. The IEEE 754 standard reserves a special value called NaN ("not a number"). NumPy's float64 can store NaN in a slot, and pandas uses it as the missing marker.
Integers have no such value, so pandas has two choices when an integer column gets a gap. It can convert the column to float64, or it can use a different storage scheme. The default is the conversion, which is called dtype promotion.
Promotion from integer to float
The constructor promotes the dtype when it sees None in an integer list. Operations that create gaps promote it too:
import pandas as pd
s = pd.Series([10, 20, 30])
print(s.dtype)
print(s.shift(1).dtype)
print(s.reindex([0, 1, 5]).dtype)The first line prints int64. The other two print float64. shift(1) pushes every value down one row and leaves a hole at the top. reindex adds a row for label 5, which has no data.
Other common sources of gaps behave the same way:
- A left merge where some rows find no match.
unstackorpivoton incomplete data.read_csvon a numeric column with empty fields.- Assigning
np.naninto an integer column.
Recent pandas 2.x releases warn about the last case. The warning says that setting an incompatible value will raise an error in a future version.
What you lose in the conversion
A float64 has 53 bits of precision for the digits of a number. Integers above 2**53 (9,007,199,254,740,992) can no longer all be represented exactly. Identifiers such as 64-bit database keys often fall in that range:
import pandas as pd
s = pd.Series([2**53 + 1])
print(s.dtype, s.iloc[0])
r = s.reindex([0, 1])
print(r.dtype, int(r.iloc[0]))The output is:
int64 9007199254740993
float64 9007199254740992The last digit changed and no error was raised. Promotion also changes how the values display, because 1 becomes 1.0. Code that later uses the column as an index, in a join, or as a string key can then produce unexpected results.
Other dtypes and their missing markers
Not every dtype promotes. Each default dtype has its own way of handling a gap:
| Column dtype | What happens with a missing value | Marker shown |
|---|---|---|
| int64 | Promoted to float64 | NaN |
| float64 | Stays float64 | NaN |
| bool | Promoted to object | None or NaN, as supplied |
| datetime64[ns] | Stays datetime64[ns] | NaT |
| object | Stays object | None or NaN, as supplied |
Here is how each case looks in code:
import pandas as pd
b = pd.Series([True, False, None])
t = pd.Series(pd.to_datetime(["2024-01-01", None]))
st = pd.Series(["a", None])
print(b.dtype, t.dtype, st.dtype)
print(t.isna().tolist())In pandas 2.x this prints object datetime64[ns] object, then [False, True].
The bool case is the costly one. A NumPy bool array has no spare value either, and NaN cannot be stored in it. Mixing True, False, and a missing value therefore forces the column to object. That brings back the pointer-per-value storage from the previous chapter. Datetimes avoid the problem because NumPy reserves a special NaT ("not a time") bit pattern for them.
For string columns the default is object, and the missing marker is whatever Python object you supplied. A column can even contain a mix of None and np.nan. The detection methods treat both as missing.
Detecting missing values consistently
Different markers behave differently. NaN is not equal to itself, so equality tests cannot find it:
import numpy as np
import pandas as pd
print(np.nan == np.nan)
print(pd.NA == 1)
print(pd.NA | True)
print(pd.NA & False)
try:
bool(pd.NA)
except TypeError as err:
print(err)This prints the following:
False
<NA>
True
False
boolean value of NA is ambiguousUse isna() and notna() (or the aliases isnull() and notnull()) instead of == np.nan. These methods recognize NaN, None, NaT, and pd.NA in one call. The same rule applies to the scalar functions pd.isna(x) and pd.notna(x).
The pd.NA output above shows a second design choice. Comparing anything with pd.NA gives <NA>, not False, because the true answer is unknown. Boolean operations follow three-valued (Kleene) logic. NA | True is True because the result is True no matter what the unknown value is. NA & False is False for the same reason. Using pd.NA directly in an if statement raises an error, because the truth of the condition is unknown.
Avoiding promotion with nullable dtypes
The extension dtypes Int64, Float64, boolean, and string can hold missing values without changing type. They are written with a capital letter (except boolean and string) to distinguish them from the NumPy dtypes. All of them use pd.NA as the marker:
import pandas as pd
s_float = pd.Series([1, 2, None])
s_nullable = pd.Series([1, 2, None], dtype="Int64")
print(s_float.dtype)
print(s_nullable.dtype)
print(s_nullable)The output is:
float64
Int64
0 1
1 2
2 <NA>
dtype: Int64Internally, a nullable integer column keeps two arrays. One holds the values and the other is a boolean mask that marks which positions are missing. Where the mask is true, the stored value is ignored. This is why the integers survive unchanged.
The price is memory. An Int64 column needs 8 bytes for each value plus 1 byte for each mask entry, so about 9 bytes per row instead of 8.
Converting existing data
There are three common ways to get nullable columns:
- Pass
dtype="Int64"(or"boolean","string","Float64") when you build the column or read the file. - Call
astype("Int64")on an existing column. - Call
convert_dtypes()on a Series or DataFrame. It looks at each column and picks the best nullable dtype.
astype("Int64") on a float column works when every non-missing value is a whole number. A value like 1.5 raises a TypeError, because the cast would lose information. If the cast fails, inspect the data. Do not force it with round, unless rounding is really what you want.
Loading files with gaps
Many data problems start at file load, because CSV has no types. A numeric column with empty fields arrives as float64 unless you say otherwise:
import io
import pandas as pd
csv = "id,qty\n1,5\n2,\n3,7\n"
df = pd.read_csv(io.StringIO(csv))
print(df.dtypes)
df2 = pd.read_csv(io.StringIO(csv), dtype={"qty": "Int64"})
print(df2.dtypes)
print(df2["qty"].sum())
print(df.convert_dtypes().dtypes)The first frame has id as int64 and qty as float64. The second keeps qty as Int64, and the sum is 12, because aggregation skips missing values by default. The convert_dtypes() call turns both columns into Int64. Note that it also converted id, which had no gaps. It does this to every column it can, so use it deliberately.
Edge cases and common errors
- Reading
float64as proof of a decimal column. A float column made only of whole numbers and NaN is often a promoted integer column. Check the source before you treat the values as measurements. - Mixed markers in object columns. A column can hold
None,np.nan, andpd.NAtogether.isna()finds all of them, but== Noneandis Nonechecks on single values do not. - Lost NaN comparisons.
df[df["x"] != 5]keeps rows wherexis NaN under NumPy-backed dtypes, becauseNaN != 5isTrue. With nullable dtypes, those rows give<NA>and are dropped from the filter. The same code can return different rows after you change the dtype. - Casting back to NumPy. Converting a nullable column with missing values to a NumPy array with
to_numpy()produces anobjectarray unless you pass adtypeand anna_value. For example,to_numpy(dtype="float64", na_value=np.nan)gives a float array. - Dropping versus filling.
dropna()removes rows, andfillna(value)replaces gaps. Filling an integer column withfillna(0)after promotion leaves it asfloat64. Cast back withastype("int64")once no missing values remain. - Library support. Some libraries expect plain NumPy arrays and may convert nullable columns to
objector reject them. Test the path from your DataFrame into the library you use.
Summary of the working model
Default NumPy-backed columns reserve one value for "missing", and only floats and datetimes have one. Integer columns promote to float64, and boolean columns fall back to object. Nullable extension dtypes avoid that with a separate mask, at the cost of extra memory and different comparison rules.
Exercise
A column of 64-bit order IDs is read from a CSV with pd.read_csv("orders.csv"). A few rows have an empty ID. After loading, two different IDs that differ only in their last digit compare as equal. What caused this, and what should you change in the read call?
Show answer
The empty fields forced the whole column to float64. IDs above 2**53 cannot be represented exactly in float64, so nearby values collapsed to the same float. Pass dtype={"id": "Int64"} (using the real column name) to read_csv, so the integers are kept exactly and the empty fields become <NA>. Reading the column as strings with dtype={"id": "string"} also works if you never do arithmetic on it.
Exercise
What dtype does pd.Series([True, False, None]) have, and why? Name a dtype that stores the same data without that problem.
Show answer
It has dtype object. A NumPy bool array has no spare value for "missing", so pandas falls back to an array of Python objects. Using dtype="boolean" stores the values with a mask and shows the gap as <NA>.
Exercise
For a column with the nullable dtype Int64, what does pd.NA == 3 return, and why is if pd.NA == 3: an error?
Show answer
It returns <NA>, because the comparison with an unknown value has an unknown answer. An if statement needs a definite True or False, and bool(pd.NA) raises a TypeError saying the boolean value of NA is ambiguous.