使用 None 的 NumPy 数组切片 [英] NumPy array slice using None
问题描述
这让我摸不着头脑.我无意中用 None 切片了一个数组并得到了除错误之外的其他东西(我预计会出现错误).相反,它返回一个具有额外维度的数组.
<预><代码>>>>导入 numpy>>>a = numpy.arange(4).reshape(2,2)>>>一种数组([[0, 1],[2, 3]])>>>[无]数组([[[0, 1],[2, 3]]])这种行为是故意的还是副作用?如果是故意的,有什么理由吗?
Using None 等同于使用 numpy.newaxis
,所以是的,这是有意的.事实上,它们是同一回事,但是,当然,newaxis
更能说明问题.
文档:
<块引用>newaxis 对象可用于所有切片操作以创建长度为 1 的轴.newaxis 是None"的别名,可以使用None"代替它,结果相同.
This had me scratching my head for a while. I was unintentionally slicing an array with None and getting something other than an error (I expected an error). Instead, it returns an array with an extra dimension.
>>> import numpy
>>> a = numpy.arange(4).reshape(2,2)
>>> a
array([[0, 1],
[2, 3]])
>>> a[None]
array([[[0, 1],
[2, 3]]])
Is this behavior intentional or a side-effect? If intentional, is there some rationale for it?
Using None is equivalent to using numpy.newaxis
, so yes, it's intentional. In fact, they're the same thing, but, of course, newaxis
spells it out better.
The newaxis object can be used in all slicing operations to create an axis of length one. newaxis is an alias for ‘None’, and ‘None’ can be used in place of this with the same result.
这篇关于使用 None 的 NumPy 数组切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!