用索引访问时,Numpy数组会改变形状

时间:2018-09-11 01:36:50

标签: numpy broadcasting

我有一个尺寸为MxNxO的小矩阵A

我有一个尺寸为KxMxNxP的大矩阵B,P> O

我有一个索引为Ox1的向量ind

我想做:

B[1,:,:,ind] = A

但是,我等式的左手

 B[1,:,:,ind].shape

的尺寸为Ox1xMxN,因此我无法向其中广播A(MxNxO)。

为什么以这种方式访问​​B会改变左侧的尺寸? 我如何轻松实现目标? 谢谢

1 个答案:

答案 0 :(得分:1)

有一个功能(即使不是错误),当在高级索引的中间混合切片时,将切片的尺寸放在末尾。

例如:

In [204]: B = np.zeros((2,3,4,5),int)
In [205]: ind=[0,1,2,3,4]
In [206]: B[1,:,:,ind].shape
Out[206]: (5, 3, 4)

3,4维已放置在ind,5之后。

我们可以通过首先用1索引,然后用其余的索引来解决:

In [207]: B[1][:,:,ind].shape
Out[207]: (3, 4, 5)
In [208]: B[1][:,:,ind] = np.arange(3*4*5).reshape(3,4,5)
In [209]: B[1]
Out[209]: 
array([[[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19]],

       [[20, 21, 22, 23, 24],
        [25, 26, 27, 28, 29],
        [30, 31, 32, 33, 34],
        [35, 36, 37, 38, 39]],

       [[40, 41, 42, 43, 44],
        [45, 46, 47, 48, 49],
        [50, 51, 52, 53, 54],
        [55, 56, 57, 58, 59]]])

仅当第一个索引是标量时才有效。如果它也是一个列表(或数组),我们将获得一个中间副本,并且无法设置这样的值。

https://docs.scipy.org/doc/numpy-1.15.0/reference/arrays.indexing.html#combining-advanced-and-basic-indexing

在其他SO问题中也有提到,尽管不是最近。

weird result when using both slice indexing and boolean indexing on a 3d array

相关问题