Sub topic 2
How missing values change dtypes
Assume you know how to create a DataFrame and select columns. You should also know basic Python types such as int, float, and str.
Missing values and dtype promotion
A pandas column has one dtype, which describes how its values are stored. A missing value can force pandas to choose a different dtype.
Traditional NumPy-backed integer columns cannot store NaN, which is a floating-point missing-value marker. Therefore, pandas promotes an integer column to float64 when you insert None or NaN.
import pandas as pd
s = pd.Series([1, 2, None])
print(s)
print(s.dtype)The dtype is float64, and the output contains NaN. The values are still displayed as 1.0 and 2.0 because the whole array now stores floating-point values.
Extension dtypes and `pd.NA`
Pandas extension dtypes add missing-value support without changing integers into floats. Int64 is a nullable integer dtype. Its capital I distinguishes it from NumPy's int64.
import pandas as pd
s = pd.Series([1, 2, None], dtype="Int64")
print(s)
print(s.dtype)
print(s.isna())The missing entry is represented by pd.NA. Pandas also provides nullable dtypes such as boolean and string.
Blocks: grouping columns internally
A DataFrame has columns that share one index. Internally, pandas may group columns with compatible dtypes into blocks. Two integer columns can share one block, while a float column and an object column usually occupy separate blocks.
This is an implementation detail. Use public operations such as dtypes and memory_usage() in application code. The private _mgr attribute is useful only for inspection and may change between pandas versions.
Measuring shallow versus deep memory
memory_usage() reports the bytes used by each column. For an object column, the default measurement counts the array of references to Python objects, not the referenced strings themselves. Use deep=True to include those objects.
import pandas as pd
df = pd.DataFrame({"city": ["Oslo", "Lima", "Pune"] * 100_000})
print(df.memory_usage(index=False))
print(df.memory_usage(index=False, deep=True))
df.info(memory_usage="deep")The deep measurement is usually the more useful estimate for object-heavy data.
Exercise
Why does pd.Series([1, 2, None]) usually become float64, and which dtype preserves integer values?
Show answer
NumPy integer arrays cannot store NaN, so pandas promotes the column to float64. The nullable Int64 extension dtype preserves integers and uses pd.NA for the missing value.