Sub topic 7
Moving between Arrow, NumPy and pandas
This chapter assumes you know the buffer layout from the earlier chapters (validity bitmap, offsets, values). It also assumes you can use NumPy arrays and pandas DataFrames. You will learn which conversions share memory, which ones copy, and how to make a silent copy fail loudly.
Why this boundary matters
Most Python data code already uses NumPy arrays or pandas DataFrames. Arrow is the format you hand data to Parquet readers, query engines and other processes. Each hop between these worlds either reuses the same memory or allocates and fills new memory. On a large column, the difference is one pointer assignment versus a full pass over the data.
A conversion can share memory only when both sides describe the column with the same bytes. A NumPy int64 array is a contiguous run of 8-byte integers. An Arrow int64 array with no nulls has a values buffer with the same bytes. Anything that differs breaks the match:
- Arrow stores missing values in a validity bitmap. NumPy integers have no missing-value marker.
- Arrow stores booleans as bits. NumPy stores one byte per boolean.
- Arrow stores strings as an offsets buffer plus a data buffer. NumPy and pandas usually store Python
strobjects.
Arrow to NumPy
Array.to_numpy takes a zero_copy_only argument. For an Array it defaults to True, so a conversion that would copy raises an error.
import numpy as np
import pyarrow as pa
values = np.array([1, 2, 3], dtype=np.int64)
arr = pa.array(values)
view = arr.to_numpy(zero_copy_only=True)
print(view)
print(np.shares_memory(values, view))
print(view.flags.writeable)The result is a view onto Arrow's values buffer, and here that buffer is the original NumPy memory. Arrow arrays are immutable, so the view is read-only. If you need to modify it, call view.copy() yourself.
Now add a null:
import pyarrow as pa
with_null = pa.array([1, None, 3], type=pa.int64())
try:
with_null.to_numpy(zero_copy_only=True)
except pa.ArrowInvalid as exc:
print("would copy:", type(exc).__name__)
print(with_null.to_numpy(zero_copy_only=False))With zero_copy_only=False, Arrow allocates a float64 array and writes nan for the null. This changes the dtype, and large integers above 2**53 lose precision when stored as float64.
The cases below decide whether to_numpy can share memory.
Table columns are ChunkedArray objects, which can hold several arrays (chunks). A column with more than one chunk cannot be a single NumPy array without concatenation. For a ChunkedArray, to_numpy always copies in that case.
NumPy to Arrow
pa.array on a primitive NumPy array wraps the existing memory instead of copying it. You saw this above with np.shares_memory. Two things can force work:
- Object arrays (for example, arrays of Python strings) must be inspected and encoded element by element.
- Missing values need a decision. NumPy has no null, so
nanis an ordinary float unless you say otherwise.
import numpy as np
import pyarrow as pa
nan_values = np.array([0.5, np.nan, 2.5])
print(pa.array(nan_values).null_count)
print(pa.array(nan_values, from_pandas=True).null_count)The first call prints 0 because nan is stored as a valid float. The second prints 1 because from_pandas=True applies pandas semantics, where nan means missing. The second call must build a validity bitmap, so it does extra work, though the values buffer can still be reused.
Arrow and pandas
Table.from_pandas and Table.to_pandas are the usual conversion pair. Each pandas column becomes an Arrow column, and nan in float columns becomes null by default.
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))The DataFrame index is also converted. A plain RangeIndex is stored only as a small description in the schema metadata, not as a column. Other indexes become extra columns, such as __index_level_0__. Pass preserve_index=False to drop the index, or True to always store it as a column. The metadata is what lets to_pandas rebuild the same index.
What copies on the way to pandas
pandas historically stores columns of the same dtype together in 2-D blocks. If a table has three int64 columns, a default to_pandas allocates one 3-by-N block and copies each column into it. Setting split_blocks=True creates one block per column, so each column can reuse its Arrow buffer.
import numpy as np
import pyarrow as pa
table = pa.table({
"a": np.arange(5, dtype=np.int64),
"b": np.linspace(0.0, 1.0, 5),
})
df = table.to_pandas(split_blocks=True, zero_copy_only=True)
print(df.shape)zero_copy_only=True makes this call raise ArrowException if any column would need a copy. Use it in pipelines where an accidental copy would be a bug. Because the DataFrame may point at Arrow memory, treat it as read-only.
For tables that cannot avoid copying, self_destruct=True lets Arrow release each column's memory right after it is converted, which lowers peak memory. The table must not be used afterward.
Types that always copy
| Arrow type | Default pandas result | Copy? |
|---|---|---|
| `int64`, `float64` without nulls | `int64`, `float64` | Can be zero-copy with `split_blocks=True` |
| Integer with nulls | `float64` with `nan` | Yes, and the dtype changes |
| `bool` | `bool` (object if nulls are present) | Yes, bits are expanded to bytes |
| `string` | `object` of Python `str` | Yes, one Python object per value |
| Timestamps | `datetime64` | Often, depending on unit and nulls |
Check the unit and nulls for timestamps instead of assuming a result.
Keeping Arrow types in pandas
The copy and dtype changes come from pandas having no native representation for these Arrow types. You can avoid them by asking pandas to keep the Arrow data with types_mapper:
import pandas as pd
import pyarrow as pa
table = pa.table({"n": pa.array([1, None, 3], type=pa.int64())})
print(table.to_pandas()["n"].dtype)
print(table.to_pandas(types_mapper=pd.ArrowDtype)["n"].dtype)The first line prints float64. The second prints int64[pyarrow], which stores the data in an Arrow array, keeps the null, and does not copy the column into NumPy memory. Use {pa.int64(): pd.Int64Dtype()}.get as the mapper if you prefer pandas' own nullable integer type, which does copy.
The trade-off is that pandas code written for NumPy-backed columns may not support Arrow-backed ones. Test the operations you depend on, since some may be slower or fall back to object conversion.
Common errors
ArrowInvalid: Needed to copy ...meanszero_copy_only=Truefound a null, a boolean, a string, or a multi-chunk column. Fix the data or passzero_copy_only=Falseand accept the copy.ValueError: assignment destination is read-onlymeans you wrote to a view of Arrow memory. Call.copy()first.- A column unexpectedly becomes
float64means integers with nulls went through defaultto_pandas. Usetypes_mapper. - A round trip changes the index. Set
preserve_indexexplicitly instead of relying on the default. - Memory doubles after
to_pandas. Arrow and pandas hold separate copies. Trysplit_blocks=True,self_destruct=True, and delete the table when you finish.
Exercise
A table has one int64 column with no nulls, stored as three chunks. Does table["x"].to_numpy() return a view of the Arrow memory? Explain, and name one way to get a single array.
Show answer
No. A NumPy array must be one contiguous block, and three separate chunks are three separate buffers, so to_numpy must concatenate them into new memory, which is a copy. To get a single array, call table["x"].combine_chunks() first (this also copies once) or build the column as a single chunk when you create it. After that, the result is a single-chunk array that to_numpy(zero_copy_only=True) can view.
Exercise
You call pa.array(np.array([1.0, np.nan])) and then pc.sum on the result. What do you get, and what changes if you pass from_pandas=True?
Show answer
Without from_pandas, nan is a valid value, so null_count is 0 and the sum is nan. With from_pandas=True, nan becomes a null, so null_count is 1 and pc.sum skips it and returns 1.0.