PyArrow の機能#
pandasはPyArrowを利用して機能を拡張し、様々なAPIのパフォーマンスを向上させることができます。これには以下が含まれます。
NumPyと比較して、より広範なデータ型
すべてのデータ型に対する欠損データサポート(NA)
高性能なIOリーダー統合
Apache Arrow仕様に基づく他のデータフレームライブラリ(例:polars、cuDF)との相互運用性を促進
この機能を使用するには、サポートされている最小限のPyArrowバージョンをインストールしてください。
データ構造の統合#
Series
、Index
、またはDataFrame
の列は、NumPy配列に似たpyarrow.ChunkedArray
によって直接バッキングできます。pandasの主要なデータ構造からこれらを構築するには、型の文字列に続けて[pyarrow]
(例:"int64[pyarrow]""
)をdtype
パラメータに渡します。
In [1]: ser = pd.Series([-1.5, 0.2, None], dtype="float32[pyarrow]")
In [2]: ser
Out[2]:
0 -1.5
1 0.2
2 <NA>
dtype: float[pyarrow]
In [3]: idx = pd.Index([True, None], dtype="bool[pyarrow]")
In [4]: idx
Out[4]: Index([True, <NA>], dtype='bool[pyarrow]')
In [5]: df = pd.DataFrame([[1, 2], [3, 4]], dtype="uint64[pyarrow]")
In [6]: df
Out[6]:
0 1
0 1 2
1 3 4
注記
文字列エイリアス"string[pyarrow]"
は、pd.StringDtype("pyarrow")
にマップされます。これはdtype=pd.ArrowDtype(pa.string())
を指定することと同等ではありません。pd.StringDtype("pyarrow")
はNumPyでバッキングされたNull許容型を返すことができ、pd.ArrowDtype(pa.string())
はArrowDtype
を返すことを除いて、一般的にデータの操作は同様に動作します。
In [7]: import pyarrow as pa
In [8]: data = list("abc")
In [9]: ser_sd = pd.Series(data, dtype="string[pyarrow]")
In [10]: ser_ad = pd.Series(data, dtype=pd.ArrowDtype(pa.string()))
In [11]: ser_ad.dtype == ser_sd.dtype
Out[11]: False
In [12]: ser_sd.str.contains("a")
Out[12]:
0 True
1 False
2 False
dtype: boolean
In [13]: ser_ad.str.contains("a")
Out[13]:
0 True
1 False
2 False
dtype: bool[pyarrow]
パラメータを受け入れるPyArrow型の場合、それらのパラメータを持つPyArrow型をArrowDtype
に渡して、dtype
パラメータで使用できます。
In [14]: import pyarrow as pa
In [15]: list_str_type = pa.list_(pa.string())
In [16]: ser = pd.Series([["hello"], ["there"]], dtype=pd.ArrowDtype(list_str_type))
In [17]: ser
Out[17]:
0 ['hello']
1 ['there']
dtype: list<item: string>[pyarrow]
In [18]: from datetime import time
In [19]: idx = pd.Index([time(12, 30), None], dtype=pd.ArrowDtype(pa.time64("us")))
In [20]: idx
Out[20]: Index([12:30:00, <NA>], dtype='time64[us][pyarrow]')
In [21]: from decimal import Decimal
In [22]: decimal_type = pd.ArrowDtype(pa.decimal128(3, scale=2))
In [23]: data = [[Decimal("3.19"), None], [None, Decimal("-1.23")]]
In [24]: df = pd.DataFrame(data, dtype=decimal_type)
In [25]: df
Out[25]:
0 1
0 3.19 <NA>
1 <NA> -1.23
すでにpyarrow.Array
またはpyarrow.ChunkedArray
がある場合は、それをarrays.ArrowExtensionArray
に渡して、関連付けられたSeries
、Index
またはDataFrame
オブジェクトを構築できます。
In [26]: pa_array = pa.array(
....: [{"1": "2"}, {"10": "20"}, None],
....: type=pa.map_(pa.string(), pa.string()),
....: )
....:
In [27]: ser = pd.Series(pd.arrays.ArrowExtensionArray(pa_array))
In [28]: ser
Out[28]:
0 [('1', '2')]
1 [('10', '20')]
2 <NA>
dtype: map<string, string>[pyarrow]
Series
またはIndex
からpyarrowのpyarrow.ChunkedArray
を取得するには、Series
またはIndex
でpyarrow配列コンストラクターを呼び出すことができます。
In [29]: ser = pd.Series([1, 2, None], dtype="uint8[pyarrow]")
In [30]: pa.array(ser)
Out[30]:
<pyarrow.lib.UInt8Array object at 0x7fac4d182ec0>
[
1,
2,
null
]
In [31]: idx = pd.Index(ser)
In [32]: pa.array(idx)
Out[32]:
<pyarrow.lib.UInt8Array object at 0x7fac4d593b80>
[
1,
2,
null
]
pyarrow.Table
をDataFrame
に変換するには、pyarrow.Table.to_pandas()
メソッドをtypes_mapper=pd.ArrowDtype
で呼び出すことができます。
In [33]: table = pa.table([pa.array([1, 2, 3], type=pa.int64())], names=["a"])
In [34]: df = table.to_pandas(types_mapper=pd.ArrowDtype)
In [35]: df
Out[35]:
a
0 1
1 2
2 3
In [36]: df.dtypes
Out[36]:
a int64[pyarrow]
dtype: object
操作#
PyArrowデータ構造の統合は、pandasのExtensionArray
インターフェースを介して実装されています。そのため、このインターフェースがpandas API内に統合されている場合に、サポートされる機能が存在します。さらに、この機能は、可能な場合はPyArrowの計算関数で高速化されます。これには以下が含まれます。
数値の集計
数値演算
数値の丸め
論理関数と比較関数
文字列関数
日付時刻関数
以下は、ネイティブのPyArrow計算関数によって高速化される操作のほんの一例です。
In [37]: import pyarrow as pa
In [38]: ser = pd.Series([-1.545, 0.211, None], dtype="float32[pyarrow]")
In [39]: ser.mean()
Out[39]: -0.6669999808073044
In [40]: ser + ser
Out[40]:
0 -3.09
1 0.422
2 <NA>
dtype: float[pyarrow]
In [41]: ser > (ser + 1)
Out[41]:
0 False
1 False
2 <NA>
dtype: bool[pyarrow]
In [42]: ser.dropna()
Out[42]:
0 -1.545
1 0.211
dtype: float[pyarrow]
In [43]: ser.isna()
Out[43]:
0 False
1 False
2 True
dtype: bool
In [44]: ser.fillna(0)
Out[44]:
0 -1.545
1 0.211
2 0.0
dtype: float[pyarrow]
In [45]: ser_str = pd.Series(["a", "b", None], dtype=pd.ArrowDtype(pa.string()))
In [46]: ser_str.str.startswith("a")
Out[46]:
0 True
1 False
2 <NA>
dtype: bool[pyarrow]
In [47]: from datetime import datetime
In [48]: pa_type = pd.ArrowDtype(pa.timestamp("ns"))
In [49]: ser_dt = pd.Series([datetime(2022, 1, 1), None], dtype=pa_type)
In [50]: ser_dt.dt.strftime("%Y-%m")
Out[50]:
0 2022-01
1 <NA>
dtype: string[pyarrow]
I/O 読み込み#
PyArrowは、いくつかのpandas IOリーダーに統合されているIO読み込み機能も提供します。以下の関数は、PyArrowにディスパッチしてIOソースからの読み込みを高速化できるengine
キーワードを提供します。
In [51]: import io
In [52]: data = io.StringIO("""a,b,c
....: 1,2.5,True
....: 3,4.5,False
....: """)
....:
In [53]: df = pd.read_csv(data, engine="pyarrow")
In [54]: df
Out[54]:
a b c
0 1 2.5 True
1 3 4.5 False
デフォルトでは、これらの関数と他のすべてのIOリーダー関数はNumPyでバッキングされたデータを返します。これらのリーダーは、パラメータdtype_backend="pyarrow"
を指定することで、PyArrowでバッキングされたデータを返すことができます。リーダーは、PyArrowでバッキングされたデータを返すために、必ずしもengine="pyarrow"
を設定する必要はありません。
In [55]: import io
In [56]: data = io.StringIO("""a,b,c,d,e,f,g,h,i
....: 1,2.5,True,a,,,,,
....: 3,4.5,False,b,6,7.5,True,a,
....: """)
....:
In [57]: df_pyarrow = pd.read_csv(data, dtype_backend="pyarrow")
In [58]: df_pyarrow.dtypes
Out[58]:
a int64[pyarrow]
b double[pyarrow]
c bool[pyarrow]
d string[pyarrow]
e int64[pyarrow]
f double[pyarrow]
g bool[pyarrow]
h string[pyarrow]
i null[pyarrow]
dtype: object
以下のようないくつかの非IOリーダー関数も、dtype_backend
引数を使用してPyArrowでバッキングされたデータを返すことができます。