DAGDA SEARCH | Back to results | Support

NumPy Integration — Apache Arrow v26.0.1

Source: https://arrow.apache.org/docs/python/numpy.html

NumPy Integration#

PyArrow allows converting back and forth from NumPy arrays to Arrow Arrays.

NumPy to Arrow#

To convert a NumPy array to Arrow, one can simply call the pyarrow.array() factory function.

>>> import numpy as np
>>> import pyarrow as pa
>>> data = np.arange(10, dtype='int16')
>>> arr = pa.array(data)
>>> arr
<pyarrow.lib.Int16Array object at ...>
[
  0,
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8,
  9
]

Converting from NumPy supports a wide range of input dtypes, including structured dtypes and both fixed-width (S and U) and variable-width (numpy.dtypes.StringDType) strings.

A StringDType array converts to string() unless large_string() or string_view() is requested with type. Missing entries become nulls:

>>> dtype = np.dtypes.StringDType(na_object=np.nan)
>>> arr = pa.array(np.array(["some", np.nan, "strings"], dtype=dtype))
>>> arr
<pyarrow.lib.StringArray object at ...>
[
  "some",
  null,
  "strings"
]

When the na_object is a string, NumPy treats missing entries as that string in every operation, and so does the conversion. Pass mask to mark values as null explicitly.

Arrow to NumPy#

In the reverse direction, it is possible to produce a view of an Arrow Array for use with NumPy using the to_numpy() method. This is limited to primitive types for which NumPy has the same physical representation as Arrow, and assuming the Arrow data has no nulls.

>>> import numpy as np
>>> import pyarrow as pa
>>> arr = pa.array([4, 5, 6], type=pa.int32())
>>> view = arr.to_numpy()
>>> view
array([4, 5, 6], dtype=int32)

For more complex data types, you have to use the to_pandas() method (which will construct a Numpy array with Pandas semantics for, e.g., representation of null values).

Timezone-aware Timestamps#

NumPy’s datetime64 type does not support timezones. When converting a timezone-aware Arrow timestamp array to NumPy via to_numpy(), the timezone information is silently dropped:

>>> arr = pa.array([1735689600, 1735689600], type=pa.timestamp("s", tz="UTC"))
>>> arr.type
TimestampType(timestamp[s, tz=UTC])
>>> arr.to_numpy()
array(['2025-01-01T00:00:00', '2025-01-01T00:00:00'],
      dtype='datetime64[s]')

If you need to preserve timezone information, there are two alternatives:

On this page Edit on GitHub