educative.io

Educative

Get Specific Indices from a Grid in numpy

I run the following code:

    import numpy as np
    Z = np.arange(9).reshape(3,3)
    print(Z[[0,1],[0,2]])

Z is:

0 1 2
3 4 5
6 7 8

I expected to get the values 1 and 2 but got 0 and 5, so I don’t understand how this indexing works.

Thanks

1 Like

You should use : print(Z[0,1:3]) , which slices the 2-D array in following manner:

Gets 0th row of 2-D array
Then, gets elements sliced from 1 to 3rd in index. ( 1 and 2 )

The way you are doing this is only applicable in fetching single element. In order to trying multiple elements, you have to add extra pair of brackets [ ]. which fetches a complete row instead of an element. For example; Z[[0,2]] will fetches 0 and 2nd row of array. i.e.
[[0 1 2]
[6 7 8]]

Sorry sir I am not satisfied with your explanation. Can you please elaborate on your answer?