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.
相关产品推荐
相关产品推荐

