使用None的NumPy数组切片 [英] NumPy array slice using None

查看:81
本文介绍了使用None的NumPy数组切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我挠了一下头.我无意中用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?

推荐答案

使用None等效于使用numpy.newaxis,因此,是有意的.实际上,它们是同一回事,但是newaxis当然会更好地说明问题.

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.

文档:

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.

一个相关的SO问题.

这篇关于使用None的NumPy数组切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆