Sub topic 2
Columnar layout: one contiguous run of values per column
This chapter assumes you can read basic Python and NumPy, and that you know what a table with rows and columns is. The previous chapter explained why data tools need a shared in-memory format. This chapter covers the main design decision in Arrow: it stores each column as its own contiguous run of values.
Rows versus columns in memory
A table is a two-dimensional idea, but computer memory is a one-dimensional sequence of bytes. Any in-memory table format has to pick an order for flattening the grid. There are two common choices.
- Row-oriented layout stores all the fields of row 0, then all the fields of row 1, and so on. Most databases use it for transactional work, and so does a Python list of dictionaries or tuples.
- Column-oriented (columnar) layout stores all the values of column 0, then all the values of column 1, and so on. Arrow uses it.
Take a table with three rows and the columns id, price and qty:
| id | price | qty |
|---|---|---|
| 1 | 9.5 | 3 |
| 2 | 7.0 | 8 |
| 3 | 4.25 | 1 |
In a row layout the bytes appear as 1, 9.5, 3, 2, 7.0, 8, 3, 4.25, 1. In a columnar layout they appear as 1, 2, 3 followed by 9.5, 7.0, 4.25 followed by 3, 8, 1.
Why contiguity helps analytical work
Analytical queries usually touch a few columns and many rows. A query such as "average price where qty is above 2" needs two columns and ignores the rest. Columnar layout helps in four ways.
- Less data is read. A scan of
pricereads only thepricebytes. In a row layout the same scan pulls every field of every row through the memory system, because the hardware loads memory in cache lines of typically 64 bytes. - Sequential access is fast. Values of one column sit next to each other, so a loop over them reads memory in order. CPUs prefetch such access patterns well.
- Vectorized instructions apply. All values in a column share one fixed-width type, so the CPU can apply SIMD (single instruction, multiple data) operations to several values at once.
- Type uniformity simplifies code. A kernel for summing
int32values has no branches for "what type is this field?". It walks a typed buffer.
These benefits are why Arrow's design is useful as a shared format. Two tools that both expect this layout can pass a buffer between them without reshaping it.
What Arrow actually stores
For a fixed-width type such as int32 or float64, one Arrow array is a validity bitmap (which tracks nulls) plus one data buffer holding the values back to back. The next chapter covers the bitmap. For now, look at the data buffer's memory layout by comparing it with a row-oriented NumPy structured array.
import numpy as np
import pyarrow as pa
# Row-oriented: each record packs id and price side by side (16 bytes per row).
rows = np.zeros(4, dtype=[("id", "i8"), ("price", "f8")])
rows["id"] = [1, 2, 3, 4]
rows["price"] = [9.5, 7.0, 4.25, 3.0]
# Looking at one field of a row-oriented array skips over the other field.
print("row layout stride:", rows["price"].strides)
# Columnar: Arrow keeps the price values in one buffer, back to back.
price = pa.array([9.5, 7.0, 4.25, 3.0], type=pa.float64())
view = price.to_numpy(zero_copy_only=True)
print("columnar stride:", view.strides)The stride is the number of bytes NumPy jumps to reach the next element. The row layout prints (16,) because each element of price is separated from the next by the 8 bytes of an id. The columnar layout prints (8,): the values are adjacent. The to_numpy call here builds a view over Arrow's own buffer, so the stride you see is the stride of the Arrow data itself.
Selecting columns costs almost nothing
Because each column owns its buffers, a table is closer to a dictionary of arrays than to a grid. Choosing a subset of columns only has to build a new list of references. Nothing needs to move.
import pyarrow as pa
table = pa.table({
"id": [1, 2, 3],
"price": [9.5, 7.0, 4.25],
"qty": [3, 8, 1],
})
narrow = table.select(["id", "price"])
original_buffer = table["price"].chunk(0).buffers()[1]
narrow_buffer = narrow["price"].chunk(0).buffers()[1]
print(narrow.column_names)
print(original_buffer.address == narrow_buffer.address)The second print shows True: both tables point at the same memory for price. This is what projection means in Arrow, and the later chapter on datasets builds on it. Selecting columns by name is cheap, and dropping unused ones early saves memory.
Variable-width and nested data stay columnar
Strings and lists have different lengths per row, so values cannot sit at fixed intervals. Arrow still keeps one column in one place. A string column uses two buffers beyond the validity bitmap. An offsets buffer holds integers marking where each string starts and ends, and a values buffer holds all the characters concatenated. The string at row i spans from offsets[i] to offsets[i + 1] in the values buffer.
For the column ["ab", "cde", "f"], the values buffer holds abcdef and the offsets are 0, 2, 5, 6. Reading one string is two offset lookups and a slice. Scanning the whole column is still a linear walk. The next chapter covers these buffers in detail.
Nested types follow the same rule, applied recursively. A list column has its own offsets, which point into a child array that holds all the list elements in one run. A struct column keeps one child array per field. Arrow does not build row-shaped objects at any level.
What columnar layout costs
The layout trades away some operations. Know these before you design around it.
- Reading one whole row touches every column. To fetch row 1000, Arrow reads one value from each column's buffer. The reads are in different places in memory, so this is slower than reading one row in a row layout. Workloads that fetch single records by key, such as an online application serving user profiles, fit row stores better.
- Arrays are immutable in practice. Buffers are sized when the array is built. Appending one row means writing to every column, and growing a buffer may mean allocating a new one and copying. Arrow offers builders to accumulate values, and you normally build arrays in bulk instead of row by row.
- Row-by-row construction is slow in Python. Calling
pa.arrayon a list of Python objects has to inspect each object. Building from a NumPy array or from existing Arrow buffers avoids this work. - Very wide tables add overhead. A table with thousands of columns carries per-column metadata and many small buffers. Row-wise operations on such a table touch thousands of locations.
Chunking: contiguous per piece, not per table
One more detail affects what "contiguous" means. A pa.Table column is a ChunkedArray, a list of one or more arrays, which Arrow calls chunks. Each chunk is contiguous. The chunks together are not required to be one buffer. This lets Arrow concatenate tables, or receive streamed batches, without copying values into one big buffer.
import pyarrow as pa
first = pa.table({"x": [1, 2, 3]})
second = pa.table({"x": [4, 5]})
combined = pa.concat_tables([first, second])
column = combined["x"]
print(column.num_chunks)
print(len(column))
print(combined.combine_chunks()["x"].num_chunks)concat_tables reports two chunks because it links the two input columns together without copying. After combine_chunks(), the data is rewritten into a single run, which costs a copy. Many kernels handle chunked input without the copy. Some code, especially code that wants a single NumPy array, forces one.
The Arrow specification also recommends that every buffer start at a 64-byte boundary and be padded to a multiple of 64 bytes. Aligned buffers suit CPU cache lines and SIMD loads. This is one reason a small array can report a larger buffer capacity than the bytes its values need.
Summary of the layout rules
- Each column is stored apart from the others, and each fixed-width column is one typed run of values.
- Nulls, offsets and nested children live in separate buffers that belong to the same column.
- Tables hold references to column buffers, so selecting, renaming and reordering columns copy no values.
- A column may be split into chunks. Each chunk is contiguous.
- The layout favors scans, aggregations and column-wise computation. It disfavors single-row lookups and frequent small appends.
Exercise
A table has 20 columns and 10 million rows. A query reads only the amount column (float64) and sums it. Compare how much value data a row layout and a columnar layout must pull through memory, assuming all 20 columns are float64. What does table.select(["amount"]) do to the buffers?
Show answer
A row layout stores 20 values of 8 bytes in each row, so the scan passes over 160 bytes per row, about 1.6 GB, to use 8 of them. A columnar layout reads only the amount buffer, 10 million times 8 bytes, which is about 80 MB. select builds a new table that references the existing amount buffer. It copies no values, so the buffer address is the same as in the original table.
Exercise
You run pa.concat_tables([t1, t2]) and the resulting column reports num_chunks == 2. You then call .to_numpy(zero_copy_only=True) on a primitive column without nulls and get an error. Why does it fail, and how do you get a single NumPy array?
Show answer
A ChunkedArray with several chunks is not one contiguous buffer, so NumPy cannot view it without joining the pieces, and zero_copy_only=True forbids that copy. Call combine_chunks() on the table or column first, which copies the values into one chunk. Then convert that chunk, or call to_numpy(zero_copy_only=False) and accept the copy.