本文介绍了是否有获取0D numpy子数组的规范方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个numpy的ndarray和一个索引:

Given a numpy ndarray and an index:

a = np.random.randint(0,4,(2,3,4))
idx = (1,1,1)

是否有一种干净的方法来检索idxa的0D子数组?

is there a clean way of retrieving the 0D subarray of a at idx?

等同于

a[idx + (None,)].squeeze()

但是没有那么干吗?

请注意,@ filippo很聪明

Note that @filippo's clever

a[idx][...]

等价于.首先,它不适用于对象数组.但更严重的是,它不会返回子数组,而是返回一个新数组:

is not equivalent. First, it doesn't work for object arrays. But more seriously it does not return a subarray but a new array:

b = a[idx][...]
b[()] = 7
a[idx] == 7
# False

推荐答案

b = a[idx+(Ellipsis,)]

我正在一台机器上进行测试,并为此编写了平板电脑,所以无法提供我通常的验证码.

I'm testing on one machine and writing this a tablet, so can't give my usual verification code.

也许最好的文档说明(或事实陈述)是:

Perhaps the best documentation explanation (or statement of fact) is:

https://docs .scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html#detailed-notes

这篇关于是否有获取0D numpy子数组的规范方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:53
查看更多