Say if I have a 2D array:
y = np.arange(35).reshape(5,7)
# array([[ 0, 1, 2, 3, 4, 5, 6],
# [ 7, 8, 9, 10, 11, 12, 13],
# [14, 15, 16, 17, 18, 19, 20],
# [21, 22, 23, 24, 25, 26, 27],
# [28, 29, 30, 31, 32, 33, 34]])
and select the 2nd and 3rd elements of the 1st, 3rd and 5th array like so:
y[np.array([0,2,4]), 1:3]
# array([[ 1, 2],
# [15, 16],
# [29, 30]])
I cannot find a way to replicate this using arrays in place of the slice for indexing, the following doesn't work, I must be able to use arrays to index as I sometimes might be interested in the 2nd and 4th elements of the arrays and so on:
y[np.array([0,2,4]), np.array([1,2])]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (2,)
How can I achieve my desired functionality?
broadcastingwith indices is the same as with addition or multiplication.np.array([1,2])[:,None] + np.array([1,2,3])produces a (2,3) sum.arr[np.array([1,2])[:,None], np.array([1,2,3])]indexes a (2,3) block.