简体   繁体   中英

Indexing 2d array with 2d array in Numpy

I have a question that bothers me for a few days. Let's assume we define a 2d array in Numpy:

x = np.array([[0, 1, 2],
              [3, 4, 5],
              [6, 7, 8]])

We also define a 1d array for indexing, let's say:

ind = np.array([2,1])

If we will try x[ind] we will get:

array([[6, 7, 8],
       [3, 4, 5]])

which makes a lot of sense: Row number 2 and row numer 1 of x .

If we will run: x[:,ind] we will get:

array([[2, 1],
       [5, 4],
       [8, 7]])

Again, it makes a lot of sense - we receive column number 2 followed by column number 1

Now we will define the index array as 2d:

ind = np.array([[2,1],
                [2,2]])

If we run x[ind] we get:

array([[[6, 7, 8],
        [3, 4, 5]],

       [[6, 7, 8],
        [6, 7, 8]]])

Again, it makes sense - for each row in the indexing 2d array we receive a 2d array that represent the corresponding rows from the original 2d array x .

However, if we run x[:,ind] we receive the next array:

array([[[2, 1],
        [2, 2]],

       [[5, 4],
        [5, 5]],

       [[8, 7],
        [8, 8]]])

I don't understand this output since it returns specific item in the indexed rows, but not the full rows. I would assume, that just like the case of x[:,ind] when it was 1d array, we will receive 2d arrays that include the original columns from the original x array.

In the last case with the indexing array:

print(ind)
array([[2, 1],
       [2, 2]])

Since ind is a 2D array of shape (2,2) , and your taking a full slice along the first axis, with ind you'll be indexing along the columns of A on each of its rows. So for instance by indexing the second row [3, 4, 5] with ind , you'll get the elements at indices 2->5 , 1->4 , 2->5 and 2->5 again, with the resulting shape being the same as ind , so [[5,4][5,5]] .

The same for each of its rows resulting in a (3,2,2) shaped array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM