python 使用 None 的 NumPy 数组切片
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1408311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NumPy array slice using None
提问by Paul
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.
这让我摸不着头脑。我无意中用 None 切片了一个数组并得到了除错误之外的其他东西(我预计会出现错误)。相反,它返回一个具有额外维度的数组。
>>> 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?
这种行为是故意的还是副作用?如果是故意的,有什么理由吗?
回答by tom10
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.
使用 None 等同于 using numpy.newaxis
,所以是的,这是有意的。事实上,它们是一回事,但是,当然,newaxis
更好地说明它。
文档:
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.
newaxis 对象可用于所有切片操作以创建长度为 1 的轴。newaxis 是 'None' 的别名,可以使用 'None' 代替它,结果相同。