Sub topic 7
Moving between Arrow, NumPy and pandas
This chapter assumes you can write basic Python, know what a pandas DataFrame is, and have read the earlier chapters on buffers, validity bitmaps, arrays and zero-copy sharing. Here you will learn when a conversion between Arrow, NumPy and pandas shares memory and when it copies.
Why conversions sometimes copy
A conversion is free only when both sides agree on the memory layout. A NumPy array is one contiguous buffer of fixed-width values. An Arrow primitive array without nulls has the same shape: one data buffer. The two can point at the same bytes.
Three things break that match:
- Nulls. Arrow records missing values in a validity bitmap. NumPy integer arrays have no such bitmap, so a missing value forces a different representation, usually floats with NaN.
- Variable-width data. Arrow strings use an offsets buffer plus a data buffer. NumPy would hold Python objects, so each value must be created.
- Chunking. A chunked array holds several buffers. NumPy needs one, so the pieces are joined.
Arrow and NumPy
The zero_copy_only=True argument turns a silent copy into an error. Use it when you need to be sure that no copy happens.
import numpy as np
import pyarrow as pa
values = np.array([1, 2, 3], dtype=np.int64)
arr = pa.array(values)
back = arr.to_numpy(zero_copy_only=True)
print(back)If you try the same call on an array with a null, pyarrow raises ArrowInvalid. Without the flag, it returns a float array with NaN in place of the null, which is a copy.
import pyarrow as pa
with_null = pa.array([1, None, 3])
print(with_null.to_numpy(zero_copy_only=False))The result is [ 1. nan 3.]. The integers became floats, so the dtype changed as well as the memory.
Arrow and pandas
Table.from_pandas and Table.to_pandas are the usual way to hand data across. These calls often copy, because pandas stores columns in blocks that may not match Arrow's per-column buffers.
import pandas as pd
import pyarrow as pa
df = pd.DataFrame({"id": [1, 2, 3], "score": [0.5, 1.5, 2.5]})
table = pa.Table.from_pandas(df)
round_trip = table.to_pandas()
print(round_trip.equals(df))This prints True for the data in this example. Treat the round trip as lossless for values, but not as free in memory.
Two details matter in practice:
from_pandasstores the pandas index as an extra column, or as metadata, depending on the index type. A default range index is saved as metadata only. A custom index becomes a column named__index_level_0__unless it has a name.- Strings in a default pandas column are Python objects. Converting them to Arrow reads each object and builds the offsets and data buffers.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ArrowInvalid` from `to_numpy(zero_copy_only=True)` | The array has nulls, is a string type, or is chunked | Drop the flag, or remove nulls first |
| Integer column became float | Nulls were filled with NaN | Keep the data in Arrow, or use a nullable pandas dtype |
| Memory doubled after `to_pandas()` | The conversion copied the data | Process in Arrow with compute functions and convert only the result |
| Unexpected extra column after a round trip | A custom pandas index was stored as a column | Call `reset_index(drop=True)` before converting, or pass `preserve_index=False` |
Exercise
You call to_numpy(zero_copy_only=True) on a pa.array([1, 2, None]) and get an error. Give the reason and one way to get a NumPy array anyway.
Show answer
The array contains a null, which Arrow stores in a validity bitmap that NumPy integer arrays cannot represent, so a zero-copy view is impossible. Call to_numpy(zero_copy_only=False) to get a copy as a float array with NaN, or fill the null first with pyarrow.compute.fill_null and then convert.