numbarrow.core.mapinarrow_factory

Overview

PySpark’s mapInArrow runs a Python function on an iterator of Arrow record batches and expects an iterator of batches back. make_mapinarrow_func() builds that function from a simpler one of yours, main_func(data_dict, bitmap_dict, broadcasts). main_func receives the columns of each batch as numpy arrays in dicts, and it returns a dict of output columns:

import pyarrow as pa
from numbarrow.core.mapinarrow_factory import Nullable, make_mapinarrow_func


def main_func(data_dict, bitmap_dict, broadcasts):
    doubled = data_dict["value"] * broadcasts["factor"]
    return {"doubled": Nullable(doubled, bitmap_dict["value"])}


udf = make_mapinarrow_func(main_func, broadcasts={"factor": 2.0})
batch = pa.RecordBatch.from_pydict({"value": [1.5, None, 4.0]})
print(next(udf(iter([batch]))).column("doubled").to_pylist())  # [3.0, None, 8.0]

Nullable pairs an output column with a validity bitmap, here the bitmap of the input column value, so that doubled is null where value is null. A plain numpy array in the returned dict becomes a column without nulls, except for a NaT, which pyarrow reads as null. The example passes no output_schema, so numbarrow infers the type of each output column from its values. In Spark, pass the same udf to df.mapInArrow(udf, "doubled double"). The built function takes any iterator of record batches, so a test can call it without Spark, as the example does.

For each batch, the built function converts every column of the batch with arrow_array_adapter(), or only the columns that the input_columns parameter names. It then calls main_func once, with three dicts:

  • data_dict maps each column’s name to its numpy data. A struct column, or a list of structs, maps to a dict of its fields: data_dict["point"]["x"] is the field x of the column point.

  • bitmap_dict has the same keys in every batch and holds the validity bitmaps, or None where a column has no validity buffer.

  • broadcasts is the dict given to make_mapinarrow_func.

For a struct column, bitmap_dict differs from what arrow_array_adapter returns. The adapter returns the struct’s own bitmap apart from the bitmaps of its fields, for is_null_struct() to read both. bitmap_dict holds no bitmap for the struct itself. numbarrow combines it into the bitmap of each field, which then also marks the rows where the whole struct is null. One is_null() call per field is therefore enough.

The README’s PySpark mapInArrow section shows a complete Spark job. Its subsections explain how to return nulls, why columns bind by position unless the output_schema parameter binds them by name, and how numbarrow chooses the types of the output columns. The reference below documents the parameters and the errors that make_mapinarrow_func raises.

Module

A factory of functions for PySpark’s mapInArrow that compute on each batch’s columns as numpy arrays.

make_mapinarrow_func() wraps a function of the caller’s, main_func, into the function that DataFrame.mapInArrow calls on each partition. For each pyarrow.RecordBatch, the wrapper adapts the columns with arrow_array_adapter() and calls main_func with the arrays and their validity bitmaps. main_func typically runs numba-compiled code on them and returns a dict of output columns, from which the wrapper builds the output batch. Nullable pairs an output column with a validity bitmap, so that the column carries nulls out. The private functions convert each output column to an Arrow array. They refuse several kinds of value that pyarrow would misread without an error, with a message that names the column.

class numbarrow.core.mapinarrow_factory.Nullable(data: object, bitmap: ndarray | None)[source]

Bases: NamedTuple

An output column paired with a validity bitmap, so that the column carries nulls out of main_func.

data is any value an output column may be: an ndarray, a list, a pyarrow.Array or a numpy record array. bitmap is a packed uint8 bitmap in the layout of the input bitmaps that main_func receives: (rows + 7) // 8 bytes, one bit per row, least significant bit first, and a set bit for a valid row. A row is null in the output if data holds a null there or its bit is clear. bitmap may also be None, the bitmap that main_func receives for an input column without a validity buffer. The column then carries only the nulls of data. A plain ndarray returned without Nullable carries no nulls out, except a NaT, which pyarrow reads as null.

bitmap: ndarray | None

Alias for field number 1

data: object

Alias for field number 0

numbarrow.core.mapinarrow_factory.make_mapinarrow_func(main_func: Callable, input_columns: list[str] | None = None, broadcasts: dict | None = None, output_schema: Schema | None = None)[source]

Return a function for DataFrame.mapInArrow that runs main_func on each batch’s columns as numpy arrays.

mapInArrow calls the returned function once per partition, with an iterator of pyarrow.RecordBatch. For each batch, the function adapts the selected columns with arrow_array_adapter() and calls main_func(data_dict, bitmap_dict, broadcasts). It builds an output batch from the dict that main_func returns, and yields it. If a column fails to adapt or to convert, the error names the column. An element of the iterator that is not a RecordBatch raises TypeError. To call the function outside Spark, pass it [batch] or table.to_batches().

Pass output_schema, derived from the schema given to mapInArrow with pyspark.sql.pandas.types.to_arrow_schema, so that the returned function takes each output column by name and converts it to its declared type. Without it, Spark binds the columns by their order in the returned dict, and pyarrow infers each type from the values.

data_dict maps the name of each selected column to its data. A struct or list-of-struct column maps to a dict of its fields, data_dict[column][field], so a field never shares a namespace with another column or with the fields of another struct. Any other column maps to one array. bitmap_dict has the same keys and shape. Each of its arrays is a packed uint8 validity bitmap. A column without a validity buffer has None in its place, and so does a struct field if neither it nor its struct has one. Every key of data_dict is in bitmap_dict, so a batch without nulls is indexed exactly like a batch with them.

The bitmap of a struct field also marks the rows where the whole struct is null. One is_null() call per field therefore sees both a null field and a null struct. For a list of structs, the field bitmaps cover the flattened struct elements, not the list rows. The adapter returns those elements without the list offsets, so a null list row could not be reported anywhere, and it would shift the mapping from elements to rows. A list column whose null_count is not zero therefore raises NotImplementedError.

main_func returns a dict that maps the name of each output column to an ndarray, a list or a pyarrow.Array. A numpy record array becomes a struct column, with one child per field. A null comes out of a list, a tuple or an object array holding None, a pyarrow.Array, a numpy masked array, and a Nullable. A plain ndarray carries no nulls out, except a NaT, which pyarrow reads as null. A row that came in null then goes out valid, with whatever main_func computed from the value stored under the null, which is 0, 0.0 or '' in a batch from Spark.

Nullable(data, bitmap) takes a bitmap in the layout of bitmap_dict, which is_null() also reads: (rows + 7) // 8 bytes of uint8, one bit per row, least significant bit first, and a set bit for a valid row. A result that is null exactly where one input column is null can pass that column’s bitmap through, as in {"out": Nullable(result, bitmap_dict["value"])}, or with bitmap_dict["column"]["field"] for a struct field. Any other result builds its own bitmap, for instance with np.packbits(valid, bitorder="little") from a boolean array valid.

A bitmap that is not a one-dimensional uint8 ndarray raises TypeError, and one of another length raises ValueError. Both errors name the column. A packed bitmap cannot tell apart row counts within one byte. A bitmap from bitmap_dict therefore raises ValueError on a column of any row count but the one it covers. That count is the batch’s rows for a column’s bitmap or a struct field’s, and the flattened elements for a field of a list of structs. A main_func that changes the length of a column needs a bitmap of its own.

Spark binds the columns of the output batch to the schema given to mapInArrow by position, not by name, and it checks nothing about their names. It reads each column with the getter of its declared type, such as getLong for LongType and TimestampType. The column’s Arrow type decides which getter works, because Spark wraps each Arrow type in an accessor that provides only one getter. The Arrow types whose accessors provide the same getter form an accessor family: int64 and timestamps share getLong, and int32 and date32 share getInt. If a column’s Arrow type is in the family of its declared type, Spark reads it without any check. An int64 column declared as a timestamp therefore reads as a timestamp, and two columns of one family swap without an error if the dict is built in the other order.

A column read through the accessor of another family fails in the JVM with java.lang.UnsupportedOperationException, whatever its width. Both float64 under LongType and int64 under DoubleType fail, though each is 64 bits wide. An int32 column under LongType fails too, because int32 provides getInt and not getLong.

The fields of a struct column are bound by position too. Without output_schema, the field order of a record array’s dtype, or the key order of the dicts, decides where each field lands: {"lat": .., "lon": ..} under struct<lon, lat> swaps the two fields without an error. Build the returned dict, and any record dtype, in the order of the declared schema, or pass output_schema, and the returned function binds the columns, and the fields of dicts and record arrays, by name.

Parameters:
  • main_func – the function to run on each batch, called as main_func(data_dict, bitmap_dict, broadcasts). It returns a dict of output columns, as described above.

  • input_columns – optional names of the columns that main_func needs in data_dict. None selects every column of the batch. A name must match exactly, case included. A name that the batch lacks raises KeyError listing the batch’s columns. A name that the batch holds more than once raises ValueError. The returned function raises both errors on the first batch. Only a batch built outside Spark can repeat a name, because mapInArrow raises an AnalysisException for a DataFrame with a repeated column name. The names are read once, when this function is called, so a one-shot iterable such as a generator works as well as a list. A name given twice is passed once. A single string raises TypeError, and an empty selection, such as a generator already used up, raises ValueError rather than passing main_func no columns. This function raises both of these when it is called, before any batch.

  • broadcasts – optional dict that every call of main_func receives as its third argument, such as parameters or lookup tables. None passes an empty dict.

  • output_schema –

    optional pyarrow.Schema of the output batches. A string column declared large_string is built as one, and a list of dicts declared as a struct is built field by field. A list of dicts or of pairs declared as a map becomes a map, which no inferred type can be cast to.

    A column that the schema names and the dict lacks raises KeyError, and a key that the schema does not name raises ValueError. A struct field that the declared type lacks raises ValueError too, whether it comes as a dict key, a namedtuple field, or a field of a record array or a pyarrow.Array. Arrow matches a dict’s keys to struct fields by exact name, so without this check it would fill the declared field with nulls. A namedtuple or pyspark Row that names the declared fields in another order raises ValueError as well, because pyarrow binds the items of a tuple by position.

    A schema that is not a pyarrow.Schema, such as a PySpark StructType, raises TypeError. A schema that repeats a name among its columns, or among the fields of one struct, raises ValueError. This function raises both of these when it is called, before any batch.

    Beyond these checks, a value is refused only if pyarrow refuses it, and pyarrow converts each shape of column its own way. A pyarrow.Array is cast to the declared type, and an ndarray of a numeric or datetime dtype goes through pa.array’s typed converter. Both raise pyarrow.ArrowInvalid for an integer out of the declared type’s range, a float with a fraction into an integer type, and a timestamp unit change that drops digits.

    A Python list, and any other sequence of Python objects such as an object-dtype ndarray, goes through pa.array’s sequence converter. It raises pyarrow.ArrowInvalid for an integer out of the declared type’s range, but OverflowError for a negative value under an unsigned type and for a value beyond the 64-bit range. except pa.ArrowInvalid does not catch the OverflowError. The sequence converter refuses a timestamp under time32 or time64 and a number under bool.

    These conversions lose data without an error:

    • a timestamp into date32 or date64;

    • a float into a narrower float, which overflows to inf;

    • from a datetime ndarray or a pyarrow.Array, a timestamp into time32 or time64, which drops the date;

    • from a numeric ndarray or a pyarrow.Array, a number into bool, which is true for anything but zero;

    • and, from a sequence of Python objects alone, a fraction into an integer type and a timestamp unit change that drops digits, which the sequence converter truncates.

    A float under a decimal type is refused on both routes of pa.array: the sequence converter takes an int or a decimal.Decimal, and the typed converter refuses a float dtype. A float pyarrow.Array is cast instead, and the cast rounds it to the declared scale.

    A datetime64 or timedelta64 ndarray is taken to a unit that pyarrow models before pyarrow reads it. A multiplier is applied, so datetime64[5s] becomes datetime64[s] with the same instants. A datetime64 hour or minute becomes seconds, and a week, month or year becomes days. A timedelta64 hour, minute, day or week becomes seconds. A unit finer than a nanosecond raises TypeError, and so does a timedelta64 month or year, which has no fixed length. If the declared type is not temporal, a change of unit raises TypeError too.

    If output_schema is None, the batch is built from the dict alone. The dict’s order decides the column order, and each type is inferred from the values. A unicode array comes back string and a bytes array binary, so a large_string input column comes back string. A datetime64 array comes back a naive timestamp of its unit after the conversion above, so datetime64[5s] comes back timestamp[s] and an hour or minute unit comes back in seconds. A day, week, month or year unit comes back date32. Spark reads a timestamp column back only in microseconds, so a datetime64 array of another unit fails in the JVM unless output_schema declares the column, which converts the unit. An object array that holds only None comes back null. The first batch’s inferred schema is held for the rest of the partition. A later batch whose inferred types differ, such as an all-None list after a list with values, or ints after floats, raises ValueError naming the column. Spark’s writer would refuse that batch without naming anything. Declare output_schema if a batch may be empty or all null.