Integer indexing of integers in multiple dimensions

I am sure that I am missing something with whole indexing and may use some help. Let's say that I am creating a 2D array:

>>> import numpy as np >>> x=np.array(range(24)).reshape((4,6)) >>> x 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]]) 

Then I can select lines 1 and 2 with

 >>> x[[1,2],:] array([[ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17]]) 

Or column 1 of rows 2 and 3 with:

 >>> x[[1,2],1] array([ 7, 13]) 

Therefore, it would be reasonable for me that I can select columns 3, 4 and 5 of rows 1 and 2 as follows:

 >>> x[[1,2],[3,4,5]] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: shape mismatch: objects cannot be broadcast to a single shape 

And instead, I need to do this in two steps:

 >>> a=x[[1,2],:] >>> a array([[ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17]]) >>> a[:,[3,4,5]] array([[ 9, 10, 11], [15, 16, 17]]) 

Based on R, my expectations seem wrong. Can you confirm that this is really not possible in one step or offer a better alternative? Thanks!

EDIT: note that my selection of rows and columns in the example occurs sequentially, but they do not have to be. In other words, fragment indexing will not be performed for my case.

+6
source share
2 answers

You also have the option of using broadcast among indexing arrays, which I usually do, rather than indexing twice, which creates an intermediate copy of your data:

 >>> x[[[1], [2]],[[3, 4, 5]]] array([[ 9, 10, 11], [15, 16, 17]]) 

To see a bit better what is happening and how to handle more indexes:

 >>> row_idx = np.array([1, 2]) >>> col_idx = np.array([3, 4, 5]) >>> x[row_idx.reshape(-1, 1), col_idx] array([[ 9, 10, 11], [15, 16, 17]]) 
+3
source

Something like that:

 In [28]: x[1:3, 3:6] Out[28]: array([[ 9, 10, 11], [15, 16, 17]]) 
+2
source

All Articles