Reputation: 1461
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)
I wanna get a 2d (3,4) shape array by the following step without loop.
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]])
I tried,
c=a[x,y,b]
but it shows
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (4,) (3,4)
and then I also tried to establish newaxis
by [:,None]
, it also doesn't work.
Upvotes: 1
Views: 4324
Reputation: 113864
Try:
>>> a[x[:,None], y[None,:], b]
array([[ 0, 21, 42, 63],
[ 84, 105, 126, 147],
[168, 189, 210, 231]])
You tried a[x,y,b]
. Note the error message:
>>> 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)
The (3,)
means that we need to extend x
to have 3 as the first dimension and 4 as the second dimension. We do this by specifying x[:,None]
(which actually allows x
to be broadcast to any size second dimension).
Similarly, the error message shows that we need to map y
to shape (3,4)
and we do that with y[None,:]
.
If one prefers, we can replace None
with np.newaxis
:
>>> a[x[:,np.newaxis], y[np.newaxis,:], b]
array([[ 0, 21, 42, 63],
[ 84, 105, 126, 147],
[168, 189, 210, 231]])
np.newaxis
is None:
>>> np.newaxis is None
True
(If I recall correctly, some earlier versions of numpy
used a different capitalization style for newaxis
. For all versions, though, None
seems to works.)
Upvotes: 5
Reputation: 23753
Similar but different, hard coded not generic.
>>> b = np.ravel(a)[np.arange(0,240,21)]
>>> b.reshape((3,4))
array([[ 0, 21, 42, 63],
[ 84, 105, 126, 147],
[168, 189, 210, 231]])
>>>
Upvotes: 1