为什么使用数组作为索引会改变多维 ndarray 的形状? [英] Why using an array as an index changes the shape of a multidimensional ndarray?

查看:33
本文介绍了为什么使用数组作为索引会改变多维 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 的形状?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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