Sub topic 1
Why Data Tools Need a Shared In-Memory Format
Prerequisites
Assume you know basic Python, tables, rows, and columns. You should also know that memory is temporary storage, while files are persistent storage.
The Data Interchange Problem
Data tools often represent the same table differently. A database driver may return rows as tuples. pandas uses its own column structures. A machine-learning library may require NumPy arrays. Moving data between these tools can require serialization, parsing, and copying.
Apache Arrow defines a language-independent format for tables in memory. Libraries can share Arrow data instead of repeatedly translating every value. This reduces overhead, especially for large tables.
Columnar Layout
Arrow stores data by column. A table with id and score keeps the IDs together and the scores together:
id: 101, 102, 103
score: 0.5, 1.5, 2.5This layout helps analytical operations. A query that needs only score can skip id. Operations over one column can also process nearby values efficiently.
A row-oriented layout stores each complete row together. That can be better when an application frequently reads or writes entire records. Arrow favors scans and transformations over selected columns.
Buffers, Validity, and Offsets
An Arrow array is built from buffers, which are regions of memory containing related binary data.
A fixed-width numeric array usually has:
- A values buffer, containing numbers at known-width positions.
- An optional validity bitmap, with one bit per element. A set bit means the value is valid.
- A null count, recording how many values are missing.
Variable-length values, such as strings, also use an offsets buffer. Each pair of offsets identifies where one string starts and ends in a shared bytes buffer.
import pyarrow as pa
arr = pa.array([1, None, 3], type=pa.int32())
print(arr.null_count) # 1
print(len(arr.buffers())) # 2Data Types and Schemas
An Arrow data type describes how bytes should be interpreted, such as int64, string, or timestamp. A schema is the named list of fields and their types. It provides a stable contract between tools.
import pyarrow as pa
schema = pa.schema([("id", pa.int64()), ("name", pa.string())])
table = pa.table({"id": [1, 2], "name": ["a", None]}, schema=schema)
print(table.schema)Exercise
Exercise
Why can a columnar format avoid reading the name column when a query requests only id?
Show answer
The values for each column are stored separately, so the scan can select only the id buffer.