没有一个工具能包办一切,所以好工具要能与其他工具对话。Polars 把表交给需要它的库用 pandas,交给文件格式或其他进程用 Arrow,交给模型用 NumPy,再把结果取回,通常无需复制数值。
用通俗的话说这个想法
我们在哪里。 前六个主题都留在 Polars 内部,这一个跨过边界再回来。pandas 是大多数 Python 数据库的通用语言,所以要弄清它的索引和日期如何对应到 Polars 的列。Arrow 是 Arrow 技能里的共享内存格式。NumPy 数组是数值代码和模型所接收的,那里有一个只读的细节会咬人。
把数据交给另一个工具时共享同一块内存而不是复制。它很快,也不占额外内存,但接收方看到的是所有者的字节,所以不能修改。
转到 pandas 再转回
to_pandas() 返回 pandas 的 DataFrame。pandas 习惯把日期放在索引里,所以用 set_index("date") 收尾。转回时 Polars 没有索引:先用 reset_index() 把它变回列,再调用 pl.from_pandas。一个意外: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:不能写入的视图
不含空值的数值列调用 series.to_numpy() 会共享 Polars 自己的内存,所以 Polars 把该数组标为只读:写入它会悄悄改写数据框。当代码需要修改数值(例如原地截断或标准化)时,请显式 .copy()。复制只花一次内存遍历的代价,却换来一个属于你自己的数组。
# 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 里,只在另一个库确实需要它自己的类型时转换一次。每一步都在 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 分