Skip to main content
 首页 » 编程设计

python之带有列表 IndexError : shape mismatch 的 Numpy 数组多维索引

2024年10月01日7zhoujg

import numpy as np 
a = np.zeros((10,20,30)) 

提取第二维和第三维的元素,ind1和ind2是索引列表

ind1 = [0,5,6] 
ind2 = [1,2,7,8] 
a[:,ind1,ind2] 

上面的命令给出了一个 IndexError: shape mismatch

如果我们做索引如下

a1 = a[:,ind1,:] 
a2 = a1[:,:,ind2] 

它有效,如果 ind1 和 ind2 的维度相同,则索引有效。

对于多维数组,索引列表是否必须具有相同的形状?

请您参考如下方法:

由于输出的形状由索引数组的形状决定,是的,它们必须相同。

或者说兼容,如下

i1, i2 = np.ix_(ind1, ind2) 
a[:, i1, i2] 

会起作用。它通过选择 ind1、ind2 的所有组合生成一个 10x3x4 数组(i1、i2 的形状为 (3, 1) (1, 4),因此它们一起广播)。

相比之下,“正常”行为(当 ind1 和 ind2 不可广播时)只是选择 ind1 和 ind2 的相应元素,这就是它们的形状必须一致的原因。

这里有一个更简单的例子来说明区别

>>> z = np.zeros((5,5), int) 
>>> a = [1,2,4] 
>>> z[a,a] = 1 
>>> z # 3 points set 
array([[0, 0, 0, 0, 0], 
       [0, 1, 0, 0, 0], 
       [0, 0, 1, 0, 0], 
       [0, 0, 0, 0, 0], 
       [0, 0, 0, 0, 1]]) 
>>> a1,a2 = np.ix_(a,a) 
>>> z[a1,a2] = 1 
>>> z # 3x3 points set 
array([[0, 0, 0, 0, 0], 
       [0, 1, 1, 0, 1], 
       [0, 1, 1, 0, 1], 
       [0, 0, 0, 0, 0], 
       [0, 1, 1, 0, 1]])