You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Polars中Series.to_numpy()未返回ndarray而是SeriesView的问题咨询

解决Polars Series.to_numpy()返回SeriesView而非numpy ndarray的问题

你操作没有错误,这是Polars 0.19.0及后续版本的默认行为:to_numpy()方法现在默认返回零拷贝的SeriesView(Polars封装的numpy兼容视图),而非直接返回numpy ndarray,这么做是为了避免不必要的数据复制,提升处理大数据集时的性能。

两种快速转成ndarray的方法

  • 方法1:调用to_numpy()时指定copy=True参数,强制生成ndarray副本:
import polars as pl
import numpy as np

s = pl.Series("a", [1, 2, 3])
arr = s.to_numpy(copy=True)
type(arr)  # 输出 <class 'numpy.ndarray'>
  • 方法2:将返回的SeriesView显式转换为ndarray:
arr = s.to_numpy()
nd_arr = np.asarray(arr)
type(nd_arr)  # 输出 <class 'numpy.ndarray'>

补充说明

SeriesView本身完全兼容numpy接口,大部分场景下可以直接当作ndarray使用(比如参与numpy运算、索引切片等)。如果不需要修改数据,建议保留SeriesView以享受零拷贝的性能优势。

内容的提问来源于stack exchange,提问作者J.N.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 09:32:07