为什么使用数组作为索引会更改多维ndarray的形状

为什么使用数组作为索引会更改多维ndarray的形状

本文介绍了为什么使用数组作为索引会更改多维ndarray的形状?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个4-D NumPy数组,轴说x,y,z,t.我想获取对应于t = 0的切片,并在y轴上排列顺序.

I have a 4-D NumPy array, with axis say x,y,z,t. I want to take slice corresponding to t=0 and to permute the order in the y axis.

我有以下内容

import numpy as np
a = np.arange(120).reshape(4,5,3,2)
b = a[:,[1,2,3,4,0],:,0]
b.shape

我得到(5,4,3)而不是(4,5,3).

I get (5, 4, 3) instead of (4,5,3).

我什么时候输入

aa = a[:,:,:,0]
bb = aa[:,[1,2,3,4,0],:]
bb.shape

我得到了预期的(4,5,3).有人可以解释为什么第一个版本交换前两个维吗?

I get the expected (4,5,3). Can someone explain why does the first version swap the first two dimensions?

推荐答案

正如@hpaulj在评论中提到的,此行为是由于混合基本切片高级索引 :

As @hpaulj mentioned in the comments, this behaviour is because of mixing basic slicing and advanced indexing:

a = np.arange(120).reshape(4,5,3,2)
b = a[:,[1,2,3,4,0],:,0]

在上面的代码片段中,发生了以下事情:

In the above code snippet, what happens is the following:

  • 当我们沿最后一个维度进行基本切片时,它会触发__getitem__调用.因此,该维度已消失. (即没有单例尺寸)
  • [1,2,3,4,0]从第二维返回5个切片.有两种可能性将此形状放在返回的数组中:在第一个位置或最后一个位置. NumPy决定将其放在第一个维度.这就是为什么在返回的形元组的第一个位置上得到5(5, ...)的原因.如果我没记错的话,Jaime在一次PyCon谈话中对此进行了解释.

  • when we do basic slicing along last dimension, it triggers a __getitem__ call. So, that dimension is gone. (i.e. no singleton dimension)
  • [1,2,3,4,0] returns 5 slices from second dimension. There are two possibilities to put this shape in the returned array: either at the first or at the last position. NumPy decided to put it at the first dimension. This is why you get 5 (5, ...) in the first position in the returned shape tuple. Jaime explained this in one of the PyCon talks, if I recall correctly.

沿第一维和第三维,由于使用:切片所有内容,因此沿这些维的原始长度得以保留.

Along first and third dimension, since you slice everything using :, the original length along those dimensions is retained.

将所有这些放在一起,NumPy返回形状元组为:(5, 4, 3)

Putting all these together, NumPy returns the shape tuple as: (5, 4, 3)

您可以在 numpy-indexing-ambiguity-in-3d-数组 arrays.indexing#combining-advanced-and-basic-indexing

这篇关于为什么使用数组作为索引会更改多维ndarray的形状?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 07:50