Sub topic 1
A DataFrame is typed columns sharing an index
Prerequisites
Assume you can create a pandas DataFrame, select columns, and recognize Python int, float, and str values. NumPy familiarity helps but is not required.
A DataFrame is typed columns sharing an index
A pandas DataFrame is a two-dimensional table. Internally, it is mainly a collection of columns that share one index. Each column stores values in an array and has a dtype, which describes the kind of values in that array.
The index labels rows, but it is separate from the column data. Columns can have different dtypes:
import pandas as pd
df = pd.DataFrame({
"a": [1, 2, 3],
"b": [1.5, 2.5, 3.5],
"c": ["x", "y", "z"],
})
print(df.dtypes)Here, a is usually int64, b is float64, and c is object in pandas 2.x.
NumPy dtypes: fixed-width values in contiguous arrays
A NumPy dtype defines how each value is represented in memory. For example, int64 uses eight bytes per value, and float64 also uses eight bytes. Values of one dtype can be stored in a compact, contiguous memory area.
This regular layout helps NumPy and pandas perform vectorized operations, meaning operations applied to whole arrays without a Python loop for every value. Fixed-width dtypes also make memory usage relatively predictable.
The dtype does not describe the meaning of a column. An int64 column might contain ages, identifiers, or counts. It describes representation and supported operations.
The object dtype: arrays of pointers to Python objects
object is a flexible dtype. Its array stores references, commonly called pointers, to separate Python objects. A string column therefore stores pointers in the array while the string objects live elsewhere.
This flexibility allows mixed Python values, but it usually costs more memory and can make operations slower than operations on fixed-width arrays. A column containing only strings may still use object; later chapters cover string and category as alternatives.
> callout note > Inspect df.dtypes early. A surprising object column often explains unexpected memory use or slow processing.
Exercise
Why can two columns with the same number of rows use different amounts of memory?
Show answer
Their dtypes can use different representations. Fixed-width numeric values have predictable sizes, while object values require separate Python objects and references.