复制您的代码以进行提问时似乎存在一些错误。
但我怀疑索引存在一个已知问题:
In [73]: a=np.zeros((2,3,4)); b=np.ones((3,4)); I=np.array([0,1])
Make I
2 个元素。索引b
给出预期的 (3,2) 形状。切片中的 3 行,来自切片的 2 列I
索引
In [74]: b[:,I].shape
Out[74]: (3, 2)
但有了 3da
我们得到转置。
In [75]: a[0,:,I].shape
Out[75]: (2, 3)
并且赋值会产生错误
In [76]: b[:,I]=a[0,:,I]
...
ValueError: array is not broadcastable to correct shape
它将 2 元素维度定义为I
首先,第 3 个元素来自:
第二。这是前面讨论过的混合高级索引的情况 - 并且还存在错误问题。 (我得查一下)。
您可能正在使用较新的numpy
(or scipy
)并收到不同的错误消息。
据记录,使用两个数组或列表进行索引,并将切片放在中间,将切片放在末尾,例如
In [86]: a[[[0],[0],[1],[1]],:,[0,1]].shape
Out[86]: (4, 2, 3)
同样的事情也发生在a[0,:,[0,1]]
。但有一个很好的论点认为事情不应该这样。
至于修复,您可以转置值,或更改索引
In [88]: b[:,I]=a[0:1,:,I]
In [90]: b[:,I]=a[0,:,I].T
In [91]: b
Out[91]:
array([[ 0., 0., 1., 1.],
[ 0., 0., 1., 1.],
[ 0., 0., 1., 1.]])
In [92]: b[:,I]=a[0][:,I]
https://github.com/numpy/numpy/issues/7030 https://github.com/numpy/numpy/issues/7030
https://github.com/numpy/numpy/pull/6256 https://github.com/numpy/numpy/pull/6256