Sub topic 2
Arrays, Record Batches, and Tables
Assume you know basic Python, tables, columns, and the difference between memory and files. The examples use pyarrow:
pip install pyarrow numpy pandasArrays, Record Batches, and Tables
An Arrow array stores one typed column. A record batch is a group of equal-length arrays with one schema. A table is a logical collection of columns and can contain multiple record batches.
import pyarrow as pa
batch = pa.record_batch(
[
pa.array([1, 2, 3], type=pa.int64()),
pa.array(["a", "b", "c"]),
],
names=["id", "name"],
)
table = pa.Table.from_batches([batch])
print(table.schema)
print(table.num_rows)The schema records each column's name and type. Arrow can represent missing values, nested values, and many types that do not map directly to ordinary Python objects.
Zero-Copy Sharing and Memory Ownership
A zero-copy conversion reuses an existing memory buffer instead of copying values. This is possible when the layouts are compatible. For example, a non-null primitive Arrow array can expose its values as a NumPy array:
import numpy as np
import pyarrow as pa
values = np.array([1, 2, 3], dtype=np.int64)
array = pa.array(values)
same_memory = array.to_numpy(zero_copy_only=True)
print(same_memory)zero_copy_only=True makes an unavailable zero-copy conversion fail instead of silently allocating. The owner of the original buffer must remain alive while the view is used.
Moving Between Arrow, NumPy, and pandas
Use pa.array and to_numpy for NumPy-compatible primitive data. Use Table.from_pandas and to_pandas when integrating with pandas. These conversions can copy data, especially for nullable or object-backed columns.
Computing on Arrow Data
Arrow compute functions operate on arrays without requiring Python loops:
import pyarrow as pa
import pyarrow.compute as pc
values = pa.array([1, 2, None, 4])
print(pc.sum(values))
print(pc.is_null(values))Most reductions, including sum, skip nulls by default. Check each function's null behavior when it affects results.
Sending Data with IPC
Arrow IPC is a language-independent format. A stream contains a schema followed by record batches. A file adds a footer and supports file-oriented access.
import pyarrow as pa
table = pa.table({"id": [1, 2], "name": ["a", "b"]})
sink = pa.BufferOutputStream()
with pa.ipc.new_stream(sink, table.schema) as writer:
writer.write_table(table)
reader = pa.ipc.open_stream(sink.getvalue())
print(reader.read_all().equals(table))Exercise
Why might to_numpy(zero_copy_only=True) fail for an Arrow array with nulls?
Show answer
NumPy's ordinary fixed-width array has no validity bitmap, so Arrow usually must create a new representation or reject the conversion.