NumPy 整合#
PyArrow 允許在 NumPy 陣列與 Arrow 陣列 之間來回轉換。
NumPy 轉 Arrow#
要將 NumPy 陣列轉換為 Arrow,只需呼叫 pyarrow.array()
工廠函數。
>>> import numpy as np
>>> import pyarrow as pa
>>> data = np.arange(10, dtype='int16')
>>> arr = pa.array(data)
>>> arr
<pyarrow.lib.Int16Array object at 0x7fb1d1e6ae58>
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
]
從 NumPy 轉換支援廣泛的輸入 dtype,包括結構化 dtype 或字串。
Arrow 轉 NumPy#
反向操作,可以使用 to_numpy()
方法,為 NumPy 產生 Arrow 陣列的視圖。這僅限於 NumPy 與 Arrow 具有相同物理表示形式的原始類型,並假設 Arrow 資料沒有空值。
>>> 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)
對於更複雜的資料類型,您必須使用 to_pandas()
方法(它將建構一個具有 Pandas 語義的 Numpy 陣列,例如,用於表示空值)。