Reputation: 55
import numpy as np
a = np.zeros((10,20,30))
To extract elements in second and third dimension, ind1 and ind2 are list of indices
ind1 = [0,5,6]
ind2 = [1,2,7,8]
a[:,ind1,ind2]
Above command gives an IndexError: shape mismatch
If we do indexing as follows
a1 = a[:,ind1,:]
a2 = a1[:,:,ind2]
it works and if the dimensions of ind1 and ind2 are same, then the indexing works.
Is it necessary that the index lists should be of same shape for multidimensional array ?
Upvotes: 2
Views: 223
Reputation: 53029
As the shape of the output is determined by the shape of the indexing array, yes, they must be the same.
Or rather compatible, the following
i1, i2 = np.ix_(ind1, ind2)
a[:, i1, i2]
will work. It produces a 10x3x4 array, by picking all combinations of ind1, ind2 (i1, i2 are shape (3, 1) (1, 4), so they are broadcast together).
The "normal" behaviour (when ind1 and ind2 are non broadcastable), by contrast, is only to pick corresponding elements of ind1 and ind2 which is why their shapes must agree.
Here's a simpler example to show the difference
>>> 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]])
Upvotes: 1
Reputation: 2284
Paul's answer probably answers your question, but I found that it won't work because you are doing both at the same time using those indexes, if you do the following:
a[:,ind1,:][:,:,ind2]
It doesn't get the index error
Upvotes: 1