すべてをこなすツールはないので、良いツールは他のツールと話せます。Polarsは、それを求めるライブラリにはpandasで、ファイル形式や別プロセスにはArrowで、モデルにはNumPyで表を渡し、結果を受け取ります。数値のコピーは通常ありません。
考え方をやさしい言葉で
ここまでの流れ。 最初の6トピックはPolarsの中にとどまりました。このトピックは境界を越えて戻ってきます。pandasはPythonのデータライブラリの多くが話す言語なので、そのインデックスと日付がPolarsの列にどう対応するかが重要です。ArrowはArrowスキルで学んだ共有メモリ形式です。NumPy配列は数値計算やモデルが受け取るもので、そこでは読み取り専用という細部が効いてきます。
データを複製せず同じメモリを共有して別のツールに渡すことです。高速で追加メモリも要りませんが、受け取る側は持ち主のバイトを見ているので、変更してはいけません。
pandasへ、そして戻る
to_pandas()はpandasのDataFrameを返します。pandasは日付をインデックスに置きたがるので、set_index("date")で仕上げます。戻るときPolarsにはインデックスがないため、pl.from_pandasの前にreset_index()で列に戻します。意外な点として、pandasのdatetime64列はPolarsでは時刻付きのDatetimeになるので、日単位にしたければpl.Dateへキャストします。
# Out to pandas (dates become the index) and back (the index becomes a column again)prices = to_pandas_prices(bars, "KO")print(type(prices).__name__, "| index:", prices.index.name, "|", len(prices), "rows | 5-day mean close:", round(prices["close"].rolling(5).mean().iloc[-1], 2))back = from_pandas_prices(prices)print(back.columns, "| date type:", back.schema["date"].base_type())
DataFrame | index: date | 6699 rows | 5-day mean close: 89.55 ['date', 'open', 'high', 'low', 'close', 'volume', 'ret'] | date type: Date
# Without the cast the dates come back as Datetime values, with a time of dayraw = pl.from_pandas(prices.reset_index())print(raw.schema["date"].base_type(), "->", back.schema["date"].base_type())
Datetime -> Date
Arrow:共有メモリ形式
PolarsはArrowのレイアウトで列を保持するため、to_arrow()は多くの場合メモリを貼り替えるだけでコピーせず、戻りのpl.from_arrowも同様です。その間はArrowを話すものなら何でも使え、Arrowスキルのpyarrow.compute関数もその一つです。こうしてPolarsの表はDuckDBやParquet書き込み、別プロセスへ低コストで渡ります。
# Filter in Arrow with pyarrow.compute, then come back to Polarsbig = big_volume_arrow(bars, 900_000_000)table = bars.to_arrow()print(type(table).__name__, table.num_rows, "rows |", type(big).__name__, big.height, "rows with volume >= 900 million")print(big.group_by("symbol").len().sort("symbol").rows())
Table 33493 rows | DataFrame 846 rows with volume >= 900 million
[('AAPL', 846)]NumPy:書き込んではいけないビュー
nullを含まない数値列のseries.to_numpy()はPolars自身のメモリを共有するため、Polarsは配列を読み取り専用にします。書き込むとフレームが黙って書き換わってしまうからです。値を変える必要があるとき、たとえばその場でのクリップや標準化では、明示的に.copy()します。コピーはメモリを1回走査するコストで、自分のものになる配列が手に入ります。
# The view is read-only; the copy can be changed and leaves the frame aloneview = bars["close"].to_numpy()mine = writable_copy(bars, "close")mine[0] = 0.0print("view writable:", view.flags.writeable, "| copy writable:", mine.flags.writeable)print("frame still starts with", bars["close"][0], "after setting the copy to", mine[0])
view writable: False | copy writable: True frame still starts with 0.83826 after setting the copy to 0.0
どの横断にもコストと型のくせがあります。インデックスから列、DateからDatetime、ビューからコピー。パイプラインはPolarsの中に保ち、別のライブラリがその型を本当に必要とする地点で1回だけ変換しましょう。毎ステップでpandasとPolarsを行き来するループは、Polarsの利点の大半を失います。
タスクの内容
- 1`to_pandas_prices`と`from_pandas_prices`絞り込み、
select、to_pandas().set_index("date")。戻りはpl.from_pandas(prices.reset_index())、dateをpl.Dateにキャストし、pct_change()をretとして追加します。 - 2`big_volume_arrow`と`writable_copy`
to_arrow()、pc.greater_equal(table["volume"], minimum)、table.filter(mask)、pl.from_arrow。そしてbars[name].to_numpy().copy()。
to_numpy()で得た配列にarr[0] = 0と書くと、読み取り専用というエラーになります。正しい対処は?ラボ:採点される内容
4タスク · 100点- 銘柄をpandasに渡す:
to_pandas_prices25点 - pandasから戻す:
from_pandas_prices25点 - Arrowで絞り込む:
big_volume_arrow25点 - 変更できるNumPy配列:
writable_copy25点