I want to index a 2D array so that the resultant array has all elements that are in any rows specified by the first index array AND any columns specified by the second index array. For example, starting with this:
In [71]: import numpy as np
In [72]: a=np.array(range(1,43)).reshape(6,7); a
Out[72]:
array([[ 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, 35],
[36, 37, 38, 39, 40, 41, 42]])
In matlab (but using python syntax here), I can do this:
b = a[[0,1,2,5],[0,3,4,6]]
and it will give me the desired 4x4 array. However, in python, this gives:
In [73]: b = a[[0,1,2,5],[0,3,4,6]]; b
Out[73]: array([ 1, 11, 19, 42])
In other words, in matlab index array behavior is identical to slice behavior, whereas in numpy, itβs not. In python, I can achieve this in a two-step process mixing slices and index arrays:
In [75]: btemp = a[:,[0,3,4,6]]; btemp
Out[75]:
array([[ 1, 4, 5, 7],
[ 8, 11, 12, 14],
[15, 18, 19, 21],
[22, 25, 26, 28],
[29, 32, 33, 35],
[36, 39, 40, 42]])
In [76]: b = btemp[[0,1,2,5],:]; b
Out[76]:
array([[ 1, 4, 5, 7],
[ 8, 11, 12, 14],
[15, 18, 19, 21],
[36, 39, 40, 42]])
which is the desired 4x4 array. It would be nice to do it in one step, but I can't find any way to do it.