Skip to content

[Python][Numba] Read and build Arrow arrays in Numba-compiled code #55904

Backlog

Description

@Alex-PLACET

Describe the enhancement requested

Let @numba.njit functions take pyarrow arrays as arguments, read them without copying, and build new Arrow arrays that are returned to Python as pa.Array.

Motivation

Writing a custom per-element loop over Arrow data from Python means choosing between:

  • pyarrow.compute: fast, but limited to the kernels that exist, logic that is data dependent or stateful cannot be expressed.
  • to_numpy() + Numba: needs a copy for nullable arrays, loses the validity bitmap, and does not work for string or binary columns.
  • Plain Python loops: correct, but orders of magnitude slower.

Numba is widely used for the "custom kernel" case with NumPy. Supporting Arrow directly would let users keep nulls, strings and decimals, avoid copies, and produce Arrow arrays as output.

Proposal

A new optional module, pyarrow.numba, active only when Numba is installed. It registers itself through Numba's numba_extensions entry point, so import pyarrow does not import Numba.

import numba as nb
import pyarrow as pa
from pyarrow.numba import Int64Builder

@nb.njit
def square_valid(a):
    b = Int64Builder()
    b.reserve(len(a))
    for i in range(len(a)):
        if a[i] is None:
            b.append(None)
        else:
            b.append(a[i] * a[i])
    return b.finish()

square_valid(pa.array([1, None, 3]))   # <pyarrow.lib.Int64Array> [1, null, 9]

Reading (zero copy)

  • len(a), a[i] (returns None for a null), is_valid(a, i).
  • Types: integers, floats, bool, date/time/timestamp/duration (as their storage integer), string/binary (and large_*), fixed_size_binary, decimal128 (as an exact (high, low) pair, with decimal_to_float).
  • Unsupported types (nested, dictionary, decimal256) raise a TypeError at compile time instead of being misread.
  • Inputs: pa.Array, and any object implementing the Arrow PyCapsule interface (__arrow_c_array__ / __arrow_c_stream__), e.g. polars, pandas, DuckDB, through register_producer(cls) or from_any(obj).

Building

  • One builder per supported type (Int8Builder … UInt64Builder, Float32/64Builder, BoolBuilder, String/LargeString/Binary/LargeBinaryBuilder) with append(value | None), reserve(n) and finish().

Component(s)

Python, C++

cc @pitrou @raulcd

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions