How can I create a NumPy array B
which is a sub-array of a NumPy array A
, by specifying which rows and columns (indicated by x
and y
respectively) are to be included?
For example:
A = numpy.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]])
x = [0, 2]
y = [1, 3, 4]
B = # Do something .....
Should give the output:
>>> B
array([[2, 4, 5], [12, 14, 15]])
The best way to do this is to use the ix_
function: see the answer by MSeifert for details.
Alternatively, you could use chain the indexing operations using x
and y
:
>>> A[x][:,y]
array([[ 2, 4, 5],
[12, 14, 15]])
First x
is used to select the rows of A
. Next, [:,y]
picks out the columns of the subarray specified by the elements of y
.
The chaining is symmetric in this case: you can also choose the columns first with A[:,y][x]
if you wish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With