英文:
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("a", [1, 2, 3])
arr = s.to_numpy()
arr
type(arr)
I get
[1 2 3]
<class 'polars.series._numpy.SeriesView'>
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.ndarray
。 np.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("a", [1, 2, 3])
arr = s.to_numpy().base
type(arr)
>>> numpy.ndarray
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论