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_dictmaps 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 fieldxof the columnpoint.bitmap_dicthas the same keys in every batch and holds the validity bitmaps, orNonewhere a column has no validity buffer.broadcastsis the dict given tomake_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:
NamedTupleAn output column paired with a validity bitmap, so that the column carries nulls out of
main_func.datais any value an output column may be: an ndarray, a list, apyarrow.Arrayor a numpy record array.bitmapis a packed uint8 bitmap in the layout of the input bitmaps thatmain_funcreceives:(rows + 7) // 8bytes, one bit per row, least significant bit first, and a set bit for a valid row. A row is null in the output ifdataholds a null there or its bit is clear.bitmapmay also beNone, the bitmap thatmain_funcreceives for an input column without a validity buffer. The column then carries only the nulls ofdata. A plain ndarray returned withoutNullablecarries no nulls out, except aNaT, 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.mapInArrowthat runsmain_funcon each batch’s columns as numpy arrays.mapInArrowcalls the returned function once per partition, with an iterator ofpyarrow.RecordBatch. For each batch, the function adapts the selected columns witharrow_array_adapter()and callsmain_func(data_dict, bitmap_dict, broadcasts). It builds an output batch from the dict thatmain_funcreturns, 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 raisesTypeError. To call the function outside Spark, pass it[batch]ortable.to_batches().Pass
output_schema, derived from the schema given tomapInArrowwithpyspark.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_dictmaps 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_dicthas the same keys and shape. Each of its arrays is a packed uint8 validity bitmap. A column without a validity buffer hasNonein its place, and so does a struct field if neither it nor its struct has one. Every key ofdata_dictis inbitmap_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 whosenull_countis not zero therefore raisesNotImplementedError.main_funcreturns a dict that maps the name of each output column to an ndarray, a list or apyarrow.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 holdingNone, apyarrow.Array, a numpy masked array, and aNullable. A plain ndarray carries no nulls out, except aNaT, which pyarrow reads as null. A row that came in null then goes out valid, with whatevermain_funccomputed from the value stored under the null, which is0,0.0or''in a batch from Spark.Nullable(data, bitmap)takes a bitmap in the layout ofbitmap_dict, whichis_null()also reads:(rows + 7) // 8bytes 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 withbitmap_dict["column"]["field"]for a struct field. Any other result builds its own bitmap, for instance withnp.packbits(valid, bitorder="little")from a boolean arrayvalid.A bitmap that is not a one-dimensional uint8 ndarray raises
TypeError, and one of another length raisesValueError. Both errors name the column. A packed bitmap cannot tell apart row counts within one byte. A bitmap frombitmap_dicttherefore raisesValueErroron 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. Amain_functhat 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
mapInArrowby position, not by name, and it checks nothing about their names. It reads each column with the getter of its declared type, such asgetLongforLongTypeandTimestampType. 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 sharegetLong, and int32 and date32 sharegetInt. 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 underLongTypeand int64 underDoubleTypefail, though each is 64 bits wide. An int32 column underLongTypefails too, because int32 providesgetIntand notgetLong.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": ..}understruct<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 passoutput_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_funcneeds indata_dict.Noneselects every column of the batch. A name must match exactly, case included. A name that the batch lacks raisesKeyErrorlisting the batch’s columns. A name that the batch holds more than once raisesValueError. The returned function raises both errors on the first batch. Only a batch built outside Spark can repeat a name, becausemapInArrowraises anAnalysisExceptionfor 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 raisesTypeError, and an empty selection, such as a generator already used up, raisesValueErrorrather than passingmain_funcno columns. This function raises both of these when it is called, before any batch.broadcasts – optional dict that every call of
main_funcreceives as its third argument, such as parameters or lookup tables.Nonepasses an empty dict.output_schema –
optional
pyarrow.Schemaof the output batches. A string column declaredlarge_stringis 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 raisesValueError. A struct field that the declared type lacks raisesValueErrortoo, whether it comes as a dict key, a namedtuple field, or a field of a record array or apyarrow.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 raisesValueErroras well, because pyarrow binds the items of a tuple by position.A schema that is not a
pyarrow.Schema, such as a PySparkStructType, raisesTypeError. A schema that repeats a name among its columns, or among the fields of one struct, raisesValueError. 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.Arrayis cast to the declared type, and an ndarray of a numeric or datetime dtype goes throughpa.array’s typed converter. Both raisepyarrow.ArrowInvalidfor 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 raisespyarrow.ArrowInvalidfor an integer out of the declared type’s range, butOverflowErrorfor a negative value under an unsigned type and for a value beyond the 64-bit range.except pa.ArrowInvaliddoes not catch theOverflowError. The sequence converter refuses a timestamp undertime32ortime64and a number underbool.These conversions lose data without an error:
a timestamp into
date32ordate64;a float into a narrower float, which overflows to
inf;from a datetime ndarray or a
pyarrow.Array, a timestamp intotime32ortime64, which drops the date;from a numeric ndarray or a
pyarrow.Array, a number intobool, 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
decimaltype is refused on both routes ofpa.array: the sequence converter takes an int or adecimal.Decimal, and the typed converter refuses a float dtype. A floatpyarrow.Arrayis cast instead, and the cast rounds it to the declared scale.A
datetime64ortimedelta64ndarray is taken to a unit that pyarrow models before pyarrow reads it. A multiplier is applied, sodatetime64[5s]becomesdatetime64[s]with the same instants. Adatetime64hour or minute becomes seconds, and a week, month or year becomes days. Atimedelta64hour, minute, day or week becomes seconds. A unit finer than a nanosecond raisesTypeError, and so does atimedelta64month or year, which has no fixed length. If the declared type is not temporal, a change of unit raisesTypeErrortoo.If
output_schemaisNone, 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 backstringand a bytes arraybinary, so alarge_stringinput column comes backstring. Adatetime64array comes back a naivetimestampof its unit after the conversion above, sodatetime64[5s]comes backtimestamp[s]and an hour or minute unit comes back in seconds. A day, week, month or year unit comes backdate32. Spark reads a timestamp column back only in microseconds, so adatetime64array of another unit fails in the JVM unlessoutput_schemadeclares the column, which converts the unit. An object array that holds onlyNonecomes backnull. 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-Nonelist after a list with values, or ints after floats, raisesValueErrornaming the column. Spark’s writer would refuse that batch without naming anything. Declareoutput_schemaif a batch may be empty or all null.