shape mismatch: indexing arrays could not be broadcast together with shapes
Asked Answered
K

1

14
j=np.arange(20,dtype=np.int)
site=np.ones((20,200),dtype=np.int)
sumkma=np.ones((100,20))

[sumkma[site[x],x] for x in range(20)]

This works, but I don't want to use for loop. When I try

sumkma[site[j],j]

I get this error:

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

How to fix the error?

Knuckleduster answered 8/9, 2017 at 20:59 Comment(2)
NumPy broadcasting aligns dimensions from right to left, not left to right.Pod
This error is commonly caused when mixing numpy's indexing methods, see this answer for a similar caseNeddy
O
13

When accessing a numpy multi-dimensional array with other multi-dimensional arrays of integer type the arrays used for the indices need to have the same shape.

Numpy will happily broadcast, if possible - but for that to be possible the arrays need to have the same dimensionality, e.g. this works:

sumkma[site[j], j[:,np.newaxis]]

The np.newaxis results in j[:,np.newaxis] being two-dimensional (shape is now (20,1), whereas shape of j is one-dimensional (20,)). It now has a shape that can be broadcasted to the shape of site[j]:

>>> j.shape
(20,)
>>> site[j].shape
(20,200)
>>> j[:,np.newaxis].shape
(20,1)

The same dimensionality for the index arrays allows numpy to broadcast them to have the same shape (20,200).

https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html#indexing-multi-dimensional-arrays

Octal answered 8/9, 2017 at 22:38 Comment(1)
j[:,np.newaxis] is equal to j.reshape(-1,1). so another answer is sumkma[site[j], j.reshape(-1,1)]Theodosia

© 2022 - 2024 — McMap. All rights reserved.