Sub topic 6
Blocks: how columns of the same dtype are grouped
This chapter assumes you can create a DataFrame, select columns, and read df.dtypes. It also assumes you know that each column has one dtype. Here you will see how pandas groups those columns internally, and why that matters for speed and memory.
From columns to blocks
A DataFrame looks like a table of independent columns. Internally, pandas keeps its data in a block manager. The manager holds a list of blocks. A block is one array that stores the values of one or more columns that share a dtype.
For numeric dtypes such as int64 and float64, a block is a 2-D NumPy array. Each row of that array is one column of the DataFrame. The manager also keeps a map from column labels to positions inside the blocks.
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))The value_counts call shows two int64 columns, one float64 column, and one object column. The block count is 3. The two int64 columns share one block. The float column and the string column each get their own.
Why grouping helps
Same-dtype columns stored together sit in one contiguous stretch of memory. This helps in two ways.
- Fast bulk operations. An operation across many columns of one dtype, such as
df[["i1", "i2"]].sum(), can run on a single array instead of looping over separate ones. - Less overhead. One array object serves many columns, so pandas keeps fewer small objects.
Extension dtypes, such as categoricals and nullable integers, are different. Each extension column normally gets its own block, because each has its own array type and cannot be packed into a shared 2-D NumPy array.
When blocks fragment
Blocks are not fixed. Operations that change the layout can split or add blocks.
- Adding a column with
df["new"] = ...often creates a new block rather than growing an existing one. - Inserting many columns one at a time can leave dozens of small blocks. pandas warns about this with a
PerformanceWarningwhen a frame becomes highly fragmented. - Calling
df.copy()consolidates same-dtype blocks into larger ones.
Many small blocks slow down operations that touch the whole frame, because pandas must visit each block. Building all columns at once, for example with pd.concat(..., axis=1) or a single dict passed to pd.DataFrame, avoids the problem.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})
for i in range(5):
df[f"c{i}"] = [i, i, i]
print(len(df._mgr.blocks)) # one block per added column
print(len(df.copy()._mgr.blocks)) # copy consolidates to one blockThe first count is 6 and the second is 1. Pandas 3.0 may change when consolidation happens, which is another reason not to rely on _mgr.
What this means in practice
- Think about dtype as the unit of storage. Two columns with the same dtype cost the same per value, and they live together.
- Mixed-dtype frames hold several arrays. Converting a whole frame with
df.to_numpy()forces a common dtype. A mix of int64 and float64 becomes float64, and any string column turns everything into object. - Row-wise operations such as
df.iloc[0]must gather one value from each block. On a mixed frame this is slower than column access, and the resulting Series has the common dtype, often object.
Exercise
A DataFrame has columns a (int64), b (int64), c (float64), d (float64), and e (object). How many blocks does a freshly built frame normally have, and why? What happens to the block count if you then add ten columns one at a time with df[name] = ...?
Show answer
It has three blocks: one int64 block holding a and b, one float64 block holding c and d, and one object block holding e. Same-dtype columns share a block. Adding ten columns one at a time usually creates a new block for each, so the count can grow toward thirteen and the frame becomes fragmented. Calling df.copy() consolidates them back into one block per dtype.