IndexError:形状不匹配:索引数组不能与形状一起广播

kin*_*hen 1 python arrays indexing numpy numpy-broadcasting

a=np.arange(240).reshape(3,4,20)
b=np.arange(12).reshape(3,4)
c=np.zeros((3,4),dtype=int)
x=np.arange(3)
y=np.arange(4)
Run Code Online (Sandbox Code Playgroud)

我想通过以下没有循环的步骤获得2d(3,4)形状数组。

for i in x:
    c[i]=a[i,y,b[i]]
c
array([[  0,  21,  42,  63],
       [ 84, 105, 126, 147],
       [168, 189, 210, 231]])
Run Code Online (Sandbox Code Playgroud)

我试过了,

c=a[x,y,b]
Run Code Online (Sandbox Code Playgroud)

但它显示

IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (4,) (3,4)

然后我还试图建立newaxis[:,None],它也不起作用。

Joh*_*024 5

尝试:

>>> a[x[:,None], y[None,:], b]
array([[  0,  21,  42,  63],
       [ 84, 105, 126, 147],
       [168, 189, 210, 231]])
Run Code Online (Sandbox Code Playgroud)

讨论区

你试过了a[x,y,b]。注意错误消息:

>>> a[x, y, b]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: shape mismatch: indexing arrays could not be broadcast
            together with shapes (3,) (4,) (3,4) 
Run Code Online (Sandbox Code Playgroud)

(3,),我们需要扩展装置x具有3为第一维和4作为第二维度。我们通过指定x[:,None](实际上允许x以任何尺寸的第二维广播)来执行此操作。

类似地,错误消息表明我们需要映射y到形状(3,4),并使用来完成y[None,:]

另类风格

如果愿意,我们可以替换Nonenp.newaxis

>>> a[x[:,np.newaxis], y[np.newaxis,:], b]
array([[  0,  21,  42,  63],
       [ 84, 105, 126, 147],
       [168, 189, 210, 231]])
Run Code Online (Sandbox Code Playgroud)

np.newaxis 是无:

>>> np.newaxis is None
True
Run Code Online (Sandbox Code Playgroud)

(如果我没记错的话,某些较早的版本numpy使用的大小写样式不同newaxis。不过,对于所有版本,None似乎都可以使用。)