Sub topic 8
Computing on Arrow data with compute functions
This chapter assumes you can read basic Python and have pyarrow installed. It also assumes you know what an Arrow array, a null and a table are from the earlier chapters. Here you will learn how pyarrow.compute works, how it treats nulls, and which errors you are likely to meet.
What a compute function is
Arrow defines a memory layout. The pyarrow.compute module, usually imported as pc, adds a library of named functions that run over that layout. Each function is a loop written in C++ over contiguous buffers. It is not a Python loop over values.
You call a function with Arrow arrays, chunked arrays, scalars or Python values. You get back a new Arrow object. Arrow data is immutable, so a compute function never changes its inputs. It allocates output buffers and fills them.
import pyarrow as pa
import pyarrow.compute as pc
arr = pa.array([1, 2, None, 4])
print(pc.sum(arr))
print(pc.is_null(arr))pc.sum returns a scalar, Int64Scalar with value 7. pc.is_null returns a boolean array of the same length: false, false, true, false.
Three kinds of function
Functions differ in how output length relates to input length. This decides how you combine them.
| Kind | Output shape | Examples |
|---|---|---|
| Element-wise (scalar) | One output value per input value, same length | `add`, `multiply`, `greater`, `utf8_upper`, `is_null` |
| Aggregate | One scalar for the whole input | `sum`, `mean`, `min_max`, `count` |
| Vector | Length can differ from the input | `filter`, `take`, `sort_indices`, `unique`, `cumulative_sum` |
Element-wise functions handle two inputs by matching positions. If the arrays have different lengths, the call fails. A scalar input is broadcast against every element of an array.
Null handling
Most functions follow one rule. If any input at a position is null, the output at that position is null. This follows from the validity bitmap. The kernel combines the input bitmaps and only computes values where the result is valid.
Aggregates differ. They skip nulls by default and take options to change that.
import pyarrow as pa
import pyarrow.compute as pc
values = pa.array([1, 2, None, 4])
print(pc.sum(values))
print(pc.sum(values, skip_nulls=False))
empty = pa.array([None, None], type=pa.int64())
print(pc.sum(empty))
print(pc.sum(empty, min_count=0))The four lines print 7, a null Int64Scalar, a null Int64Scalar, and 0. min_count is the smallest number of non-null values needed to produce a result. The default is 1, so an all-null input gives null. Setting it to 0 gives the identity value for sum.
To replace nulls before computing, use pc.fill_null. To test for them, use pc.is_null or pc.is_valid.
Element-wise work on a table
A table column is a ChunkedArray, a list of arrays that acts as one column. Compute functions accept chunked arrays and return chunked arrays. You do not have to merge chunks first.
import pyarrow as pa
import pyarrow.compute as pc
table = pa.table({
"item": ["a", "b", "c", "d"],
"price": [2.5, 10.0, None, 4.0],
"qty": [4, 1, 3, None],
})
qty_f = pc.cast(table["qty"], pa.float64())
total = pc.multiply(table["price"], qty_f)
table = table.append_column("total", total)
mask = pc.greater(table["total"], 5.0)
big = table.filter(mask)
print(big.num_rows)
print(big["item"].to_pylist())Rows c and d have a null in price or qty, so their total is null. The comparison also gives null for them. Table.filter drops rows where the mask is null by default, so two rows remain: ['a', 'b'].
If you want null mask entries kept, pass null_selection_behavior="emit_null". That produces rows of nulls. It rarely helps, but it explains why filtered row counts sometimes surprise people.
The explicit pc.cast call is deliberate. Many functions cast mixed numeric types for you, but explicit casts keep the result type predictable.
Choosing between values with `if_else`
pc.if_else(cond, left, right) picks element-wise. It is the vectorized form of a Python conditional.
import pyarrow as pa
import pyarrow.compute as pc
score = pa.array([35, 72, None, 90])
passed = pc.greater_equal(score, 50)
label = pc.if_else(passed, "pass", "fail")
print(label.to_pylist())This prints ['fail', 'pass', None, 'pass']. The null condition produces a null result. Use pc.fill_null(passed, False) first if you want unknown scores labelled fail.
Grouped aggregation and sorting
Plain aggregates reduce a whole column. To aggregate per key, use Table.group_by, which runs on the Arrow compute engine.
import pyarrow as pa
sales = pa.table({
"region": ["east", "west", "east", "west", "east"],
"amount": [10, 20, 30, None, 50],
})
result = sales.group_by("region").aggregate([("amount", "sum"), ("amount", "count")])
print(result.column_names)
print(result.num_rows)The result has columns amount_sum, amount_count and region. It has two rows. Do not rely on the order of the groups. Sort the result if the order matters.
pc.sort_indices returns the positions that would sort the data. You apply them with take. The two steps let you sort one column and reorder many.
import pyarrow as pa
import pyarrow.compute as pc
t = pa.table({"name": ["x", "y", "z"], "score": [3, None, 9]})
order = pc.sort_indices(t, sort_keys=[("score", "descending")])
print(t.take(order)["name"].to_pylist())This prints ['z', 'x', 'y']. Nulls sort last by default.
Strings and options
String functions work on the offsets and values buffers described earlier. They avoid creating one Python string per row.
import pyarrow as pa
import pyarrow.compute as pc
names = pa.array(["Ada", "grace", None, "Linus"])
print(pc.utf8_upper(names).to_pylist())
print(pc.utf8_length(names).to_pylist())
print(pc.match_substring(names, "a").to_pylist())The outputs are ['ADA', 'GRACE', None, 'LINUS'], [3, 5, None, 5] and [False, True, None, False]. match_substring is case-sensitive unless you pass ignore_case=True.
Functions with settings take them as keyword arguments, as in pc.round(x, ndigits=1). Under the hood these become option objects such as ScalarAggregateOptions. You can also pass the option object directly.
You can call a function by its registered name, which helps when the name is stored as data:
import pyarrow as pa
import pyarrow.compute as pc
a = pa.array([1, 2, 3])
b = pa.array([10, 20, 30])
print(pc.call_function("add", [a, b]).to_pylist())This prints [11, 22, 33].
Common errors
Type mismatch. pc.add(pa.array([1]), pa.array(["a"])) raises ArrowNotImplementedError, because no kernel adds integers to strings. Cast first.
Silent integer overflow. add, subtract and multiply wrap around on overflow, as C integers do. The _checked variants raise instead.
import pyarrow as pa
import pyarrow.compute as pc
big = pa.array([2**63 - 1], type=pa.int64())
one = pa.array([1], type=pa.int64())
print(pc.add(big, one).to_pylist())
try:
pc.add_checked(big, one)
except pa.ArrowInvalid as err:
print("overflow:", err)The first print shows [-9223372036854775808]. The second raises and prints the overflow message. Use _checked when wrong numbers are worse than a failed job.
Length mismatch. Two arrays of different lengths passed to an element-wise function raise ArrowInvalid. Scalars broadcast, arrays do not.
Assuming a Python scalar. pc.sum(arr) returns a pa.Scalar. Call .as_py() to get a Python number or None.
Where compute functions are used next
The same function names appear in expressions for dataset scans. pc.field("price") > 3 builds a lazy expression instead of computing a result. A scan applies it as files are read. The next chapters use this idea.
Exercise
Given x = pa.array([5, None, 15]), what does pc.sum(x) return, and what changes if you call pc.sum(x, skip_nulls=False)?
Show answer
pc.sum(x) returns an Int64Scalar with value 20, because the null is skipped. With skip_nulls=False, the null makes the whole result a null Int64Scalar.
Exercise
A table has columns a and b, both int64. You want rows where a + b is greater than 100, and you must not let overflow go unnoticed. Which functions do you chain, and what happens to rows where a or b is null?
Show answer
Compute s = pc.add_checked(table["a"], table["b"]), then mask = pc.greater(s, 100), then table.filter(mask). Rows with a null in a or b give a null sum and a null mask value, so filter drops them by default.