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

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

问题描述

这让我摸不着头脑.我无意中用 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"代替它,结果相同.

一个相关的 SO 问题.

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 docs:

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.

A related SO question.

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

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