Polars Series.to_numpy() 不返回 ndarray。

huangapple go评论93阅读模式
英文:

Polars Series.to_numpy() does not return ndarray

问题

我尝试通过.to_numpy()将Series转换为numpy数组,但与文档显示的不同,我得到的不是ndarray,而是seriesview。

在文档中运行示例:
https://pola-rs.github.io/polars/py-polars/html/reference/series/api/polars.Series.to_numpy.html

s = pl.Series("a", [1, 2, 3])
arr = s.to_numpy()
arr
type(arr)

我得到

[1 2 3]
<class 'polars.series._numpy.SeriesView'>

我在这里做错了什么,如果没有,我应该怎样解决这个问题?

英文:

I was trying to convert a series to a numpy array via .to_numpy() but unlike what the documentation shows i am not getting a ndarray out but a seriesview

Running exactly the example in the documentation: https://pola-rs.github.io/polars/py-polars/html/reference/series/api/polars.Series.to_numpy.html

s = pl.Series(&quot;a&quot;, [1, 2, 3])
arr = s.to_numpy()
arr
type(arr)

I get

[1 2 3]
&lt;class &#39;polars.series._numpy.SeriesView&#39;&gt;

Am i doing something wrong here and if not how should i work around this?

答案1

得分: 3

看起来文档有误。 Series.to_numpy()确实返回series._numpy.SeriesView对象,但是通过查看 源代码series._numpy.SeriesView继承了np.ndarray类,并且只是为了内部目的而向该类添加了另一个属性。

所以在所有情况下,你无需做任何操作。你可以将Series.to_numpy()的返回值视为np.ndarray,因为每个polars.series._numpy.SeriesView也是np.ndarraynp.ndarray对象具有的任何方法或属性,也将存在于polars.series._numpy.SeriesView对象中。

英文:

It looks like the documentation is incorrect. Series.to_numpy() does return a series._numpy.SeriesView object, however by looking at the source code, series._numpy.SeriesView inherits the np.ndarray class and just adds another attribute to the class for internal purposses.

So for all purposes, there's nothing you need to do. You can treat the return value of Series.to_numpy() as a np.ndarray because every polars.series._numpy.SeriesView is also a np.ndarray. Any method or attribute that an np.ndarray object has, it will also be present on a polars.series._numpy.SeriesView object.

答案2

得分: 0

如果您想访问实际的NumPy数组而不进行额外的复制,您可以使用.base属性。

s = pl.Series("a", [1, 2, 3])
arr = s.to_numpy().base
type(arr)
>>> numpy.ndarray
英文:

If you want to access the actual numpy array without making additional copies you can use the .base attribute.

s = pl.Series(&quot;a&quot;, [1, 2, 3])
arr = s.to_numpy().base
type(arr)
&gt;&gt;&gt; numpy.ndarray

huangapple
  • 本文由 发表于 2023年5月28日 20:43:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76351556.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定