Sub topic 5
Arrays, record batches and tables
This chapter covers the four containers pyarrow uses to hold data: Array, ChunkedArray, RecordBatch and Table. It assumes you have read the earlier chapters on buffers and on types and schemas. You should know that an array is a typed sequence stored in buffers and that a schema lists named, typed fields. You should also be comfortable with basic Python and with tables, rows and columns from pandas or SQL.
Four containers, one idea
A column of values lives in an array. Everything else is a way of grouping arrays under a schema. The choice between containers depends on two questions: do you have one column or several, and is each column stored in one piece or in several?
| Container | Holds | Columns | Pieces per column | Typical use |
|---|---|---|---|---|
| `Array` | One sequence of values of one type | 1 | 1 | Building blocks, compute results |
| `ChunkedArray` | A list of arrays of the same type | 1 | Many | A column inside a table |
| `RecordBatch` | Equal-length arrays plus a schema | Many | 1 | Streaming, IPC messages |
| `Table` | A schema plus chunked arrays | Many | Many | Whole datasets in memory |
Arrays
An Array is a fixed-length, immutable sequence of values of one data type. You create one from Python data, and pyarrow infers the type unless you pass one.
import pyarrow as pa
ids = pa.array([1, 2, 3], type=pa.int64())
names = pa.array(["a", None, "c"])
print(ids.type, len(ids))
print(names.type, names.null_count)
print(names.to_pylist())names is inferred as string, and its null_count is 1. Arrays are immutable. Assigning with ids[0] = 5 raises a TypeError. To change values you build a new array, usually with a compute function (covered in a later chapter). Immutability is what makes it safe for several arrays, tables and even libraries to share the same buffers.
Slicing is a view
Slicing an array does not copy values. It creates a new array object that points into the same buffers with a different offset and length.
import pyarrow as pa
arr = pa.array([10, 20, 30, 40, 50])
part = arr.slice(1, 3)
print(part.to_pylist())
print(part.offset, len(part))This prints [20, 30, 40], then an offset of 1 and a length of 3. The original five values stay alive in memory as long as part exists.
Record batches
A RecordBatch is a set of equal-length arrays plus a schema, which gives each array a name. It is the unit of exchange in Arrow: IPC streams, Flight and the C data interface all move data as sequences of record batches.
import pyarrow as pa
ids = pa.array([1, 2, 3], type=pa.int64())
names = pa.array(["a", None, "c"])
batch = pa.record_batch([ids, names], names=["id", "name"])
print(batch.num_rows, batch.num_columns)
print(batch.schema)
print(batch.column(0))
print(batch.column("name").to_pylist())A batch has no chunking. Every column is exactly one array, so a batch is cheap to reason about: row i is at index i in every column. If the arrays differ in length, pyarrow raises ArrowInvalid.
Batches are a good size for streaming and for parallel work, since one batch can be handed to one worker. Many engines choose batch sizes that fit in CPU cache, often thousands to a million rows. Arrow does not fix a size.
Tables
A Table is a schema plus one ChunkedArray per field. Each chunked array is a list of ordinary arrays. The chunks do not have to be the same lengths from column to column, but the rows are logically aligned, so the sum of chunk lengths must be the same for every column.
The next example builds a table from a dictionary and pins the schema explicitly.
import pyarrow as pa
schema = pa.schema([
("id", pa.int64()),
("name", pa.string()),
])
table = pa.table({"id": [1, 2, 3], "name": ["a", None, "c"]}, schema=schema)
print(table.schema)
print(table.num_rows)
print(table.num_columns)
print(type(table.column("id")))table.column("id") returns a ChunkedArray, not an Array. This surprises people who expect a column to be a single run of values. Even a table built from a single dictionary holds each column as a chunked array, usually with one chunk.
Passing schema= is worth the extra lines. Without it, pyarrow infers types from the data, and a column of Python ints becomes int64 while a column containing only None becomes the null type. With a schema, values that do not fit the declared type raise an error at construction, and you find the problem at the source. A field declared with nullable=False also rejects None.
Why tables have chunks
Chunking lets a table grow without copying. Concatenating two tables just builds new chunked arrays that list the chunks of both.
import pyarrow as pa
t1 = pa.table({"id": [1, 2], "name": ["a", "b"]})
t2 = pa.table({"id": [3], "name": ["c"]})
combined = pa.concat_tables([t1, t2])
print(combined.num_rows)
print(combined.column("id").num_chunks)
flat = combined.combine_chunks()
print(flat.column("id").num_chunks)The first count is 2 chunks, and after combine_chunks() it is 1. concat_tables copies no values, but it requires the schemas to match. combine_chunks() does copy, because it must lay the values out contiguously in new buffers.
Chunking also arises on its own. Reading a Parquet file, scanning a dataset or receiving an IPC stream typically produces one chunk per record batch or row group. So tables you did not build yourself are often chunked.
Moving between batches and tables
Tables and batches convert both ways, and neither direction copies values.
import pyarrow as pa
table = pa.table({"id": [1, 2, 3, 4, 5]})
batches = table.to_batches(max_chunksize=2)
print([b.num_rows for b in batches])
rebuilt = pa.Table.from_batches(batches)
print(rebuilt.equals(table))The batch sizes come out as [2, 2, 1]. to_batches splits at chunk boundaries and also caps each batch at max_chunksize rows. from_batches requires every batch to share one schema.
Common errors and edge cases
- Mismatched lengths.
pa.record_batchandpa.tableraiseArrowInvalidwhen columns have different lengths. Check lengths before building, especially when you assemble columns from different sources. - Mismatched schemas on concatenation.
pa.concat_tablesfails if the field names or types differ. A common cause is one table withint64and another withint32for the same column. Cast one table first withtable.cast(target_schema). - Treating a column as an array. Code written for
Arraycan fail on aChunkedArray. Methods liketo_numpywork on both, but a multi-chunk column must be copied into one buffer, so a zero-copy request fails there. The next chapters cover the conversion rules. - Many tiny chunks. Appending one-row tables in a loop produces thousands of chunks. Each chunk adds per-chunk overhead to every operation. Collect the rows and build the table once, or call
combine_chunks()after the loop. - Mutating by habit. Methods such as
append_column,set_columnanddrop_columnsreturn a new table. The original is unchanged. They are cheap, since they reuse the existing column buffers and only add or swap references. - Empty tables. A table with zero rows can have a column with zero chunks. Code that reads
column.chunk(0)will fail on such a table, so checknum_chunksfirst.
Building from other shapes
Beyond dictionaries, a table can be built from a list of row dictionaries with pa.Table.from_pylist, or from a list of arrays with pa.Table.from_arrays.
import pyarrow as pa
rows = [
{"id": 1, "name": "a"},
{"id": 2, "name": "b"},
]
from_rows = pa.Table.from_pylist(rows)
from_cols = pa.Table.from_arrays(
[pa.array([1, 2]), pa.array(["a", "b"])],
names=["id", "name"],
)
print(from_rows.equals(from_cols))Row-oriented input is convenient but slow for large data. pyarrow must inspect each Python object to infer types and write it into column buffers. For large data, build columns from NumPy arrays, from files or from other Arrow sources, which avoids per-value Python work.
Exercise
A table has a column id made of 3 chunks. You call table.to_batches() and then pa.Table.from_batches(...) on the result. Does column("id") have 1 chunk or 3 chunks afterward, and was any value data copied? Then explain why pa.concat_tables([t1, t2]) fails when t1.id is int64 and t2.id is int32.
Show answer
It still has 3 chunks, because each chunk becomes a batch and each batch becomes a chunk, and no value data is copied since only references to the existing arrays are regrouped. concat_tables fails because it needs identical schemas, and int64 and int32 are different types. Cast one table to the other's schema first, for example t2.cast(t1.schema), then concatenate.
Exercise
You slice 10 values out of a 100-million-row array with arr.slice(0, 10), store the slice in a long-lived cache and drop arr. Why might memory stay high, and how do you fix it?
Show answer
A slice is a view that shares the parent's buffers, so the parent's 100 million values stay alive as long as the slice does. Make an independent copy of the small piece, for example pa.concat_arrays([part]), and cache that instead.