Sub topic 6
Blocks: how columns of the same dtype are grouped
This chapter assumes you know that each column has a dtype, that numeric NumPy dtypes are fixed-width, and that the object dtype stores pointers. It also assumes you can build a DataFrame from a dict. Earlier chapters covered all of that. Here you will look one layer down, at how the DataFrame arranges its columns in memory.
From columns to blocks
At the user level, a DataFrame is a set of named columns that share one row index. Each column has one dtype. Internally, pandas does not keep one array per column. A component called the block manager groups columns that have the same dtype into a block. A block is one two-dimensional array that holds several columns.
The layout looks like this:
- A block of
int64columns is one NumPy array of shape(number_of_columns, number_of_rows). - The block manager records which block holds each column and at which row of that block.
- The index and the column labels are stored separately, as axes of the manager.
The block array has columns as rows, which can look backwards. It is stored this way so that each column is a contiguous run of memory. Reading one column is then a cheap slice of one block row.
Seeing the blocks
The _mgr attribute exposes the manager. It is private, so use it to learn and inspect, and never in production code. Its behavior can change between versions.
import pandas as pd
df = pd.DataFrame({
"i1": [1, 2, 3],
"i2": [4, 5, 6],
"f1": [0.1, 0.2, 0.3],
"s1": ["a", "b", "c"],
})
print(df.dtypes.value_counts())
# _mgr is a private attribute and may change between versions.
print(len(df._mgr.blocks))
for block in df._mgr.blocks:
print(block.dtype, block.values.shape)value_counts() shows two int64 columns, one float64 column and one object column. There are three blocks, one per distinct dtype. The loop prints the shape of each block's array. The integer block has shape (2, 3), which means two columns and three rows. The other two blocks have shape (1, 3). The order of the blocks can differ between versions.
The number of blocks is at least the number of distinct dtypes. It can be larger, as the fragmentation section below shows.
Extension dtypes get their own block
The grouping applies to NumPy-backed dtypes. A column with an extension dtype such as Int64, boolean, category, or a timezone-aware datetime is stored as an extension array. These arrays are one-dimensional and are not stacked into a shared 2D array. Each extension column normally sits in a block of its own.
import pandas as pd
df = pd.DataFrame({
"a": pd.array([1, 2, 3], dtype="Int64"),
"b": pd.array([4, 5, 6], dtype="Int64"),
"c": [7, 8, 9],
"d": [10, 11, 12],
})
print(df.dtypes)
# _mgr is a private attribute and may change between versions.
print(len(df._mgr.blocks))The two Int64 columns have the same dtype, but they do not share a block. The two int64 columns do. The expected block count is therefore 3: one block for c and d, and one each for a and b.
Having many extension columns therefore means having many blocks. This is rarely a problem for correctness. It does mean that operations that treat all same-dtype columns as one array lose their advantage on those columns.
Why pandas groups columns this way
Blocks are a trade-off, and each side shows up in everyday code.
Operations that touch every column of one dtype run on a single array. Adding a scalar to a frame of 50 float64 columns can be one vectorized NumPy call over one (50, n) array. Without blocks it would be 50 separate calls. Reductions such as df.sum() and arithmetic between frames benefit in the same way.
Conversion to NumPy is cheap for uniform frames. df.to_numpy() on a frame whose columns all have one NumPy dtype can use that block's array, transposed, instead of copying element by element. On a mixed frame pandas must find a common dtype and copy. Integers and floats become float64. Add a string column and everything becomes object, which is why to_numpy() on mixed frames is slow and memory-hungry.
Row access is awkward. Taking one row with df.iloc[0] has to pull one value from each block and combine them into a Series with a common dtype. For a mixed frame that dtype is usually object. Looping over rows with iloc or iterrows() is slow partly for this reason. Column-oriented code matches the layout.
| Operation | Cost on the block layout |
|---|---|
| Select one column | Cheap slice of a block |
| Apply a function to all columns of one dtype | One call on a 2D array |
| Take one row of a mixed frame | Gathers one value per block, often upcasts to `object` |
| `to_numpy()` on a uniform frame | Can avoid a copy |
| `to_numpy()` on a mixed frame | Copies to a common dtype |
Fragmentation and consolidation
When you build a frame in one step, as in the first example, pandas creates one block per dtype. When you add columns one at a time with df["new"] = ..., each new column usually becomes its own block. The manager does not merge it into the existing block on every insertion, because merging would copy the whole block each time. Merging is called consolidation, and pandas does it lazily, for example when an operation needs it.
A frame with a large number of one-column blocks is fragmented. Per-block overhead grows, and operations that loop over blocks slow down. Once the block count passes 100, pandas emits a PerformanceWarning on insertion that says the frame is highly fragmented.
import warnings
import numpy as np
import pandas as pd
n = 1_000
df = pd.DataFrame({"base": np.arange(n)})
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
for i in range(150):
df[f"col{i}"] = np.arange(n)
# _mgr is a private attribute and may change between versions.
print(len(df._mgr.blocks))
print(any(issubclass(w.category, pd.errors.PerformanceWarning) for w in caught))
merged = df.copy()
print(len(merged._mgr.blocks))
built = pd.DataFrame({f"col{i}": np.arange(n) for i in range(151)})
print(len(built._mgr.blocks))All 151 columns are int64, yet the loop leaves the frame with a block count above 100, and the warning is raised. df.copy() consolidates the blocks, and the block count typically drops to 1. Building the frame from a dict of columns also produces one block.
The fix is usually in how you build the frame:
- Collect the new columns in a dict, then create the DataFrame once, or join them with
pd.concat(..., axis=1). - If you must add columns in a loop, call
df.copy()afterwards to consolidate. - Avoid inserting hundreds of columns one by one when a single construction call would do.
Blocks and memory
Grouping columns does not change how many bytes the data takes. An int64 column needs 8 bytes per row whether it sits alone or inside a block of ten columns. What blocks change is the speed of operations, and sometimes temporary memory use, because a consolidation or a to_numpy() on mixed dtypes allocates new arrays.
The memory savings come from changing dtypes, which later chapters cover with categoricals, downcasting and load-time dtypes. Changing a column's dtype also moves it between blocks. If you cast an int64 column to int32, it leaves the int64 block and joins an int32 block, and the old block is rebuilt or shrunk. Each distinct dtype you introduce can add a block.
Limits of this model
_mgris private. The structure described here is an implementation detail. Learn it to predict performance, but do not write code that depends on_mgr,blocks, or block shapes.- Views and copies. Because columns of one dtype live in one array, selecting a column can return a view of part of a block instead of a copy. Whether a later write affects the original frame depends on pandas' view and copy rules, which are the subject of a later chapter on Copy-on-Write.
- Version differences. The exact moments when pandas consolidates have changed across releases, and the default string dtype changes in pandas 3. A string column is then not
object, but it is still outside the NumPy numeric blocks. The principle holds in every version: same-dtype NumPy columns can share a block, and extension columns generally do not.
To check how a real frame is laid out, count blocks with _mgr in an interactive session. Then judge by timing the operation that matters to you, not by block counts alone.
Exercise
A frame has these columns: two float64, three int64, one Int64 (nullable) and one column of Python strings stored as object. About how many blocks does it have right after construction from a dict, and what could you do if you later added 200 more columns one at a time and saw a PerformanceWarning?
Show answer
There are four blocks: one for the two float64 columns, one for the three int64 columns, one for the Int64 extension column, and one for the object column. Adding 200 columns one at a time leaves many one-column blocks and triggers the fragmentation warning. Fix it by gathering the new columns in a dict and building the frame once. Alternatively, call df.copy() after the loop to consolidate the blocks.
Exercise
Why does to_numpy() on a frame of only float64 columns tend to be cheap, while the same call on a frame that mixes integers and strings is expensive?
Show answer
A frame of only float64 columns can have its single block exposed as one array without converting any values, so the call can avoid a copy. A mixed frame has no single NumPy dtype that fits every column, so pandas must convert everything to a common dtype, here object. That allocates a new array and creates a Python object for each value.