Index a numpy array with another array

前端 未结 2 1726
春和景丽
春和景丽 2021-01-18 02:19

I feel silly, because this is such a simple thing, but I haven\'t found the answer either here or anywhere else.

Is there no straightforward way of indexing a numpy

相关标签:
2条回答
  • 2021-01-18 02:46

    That is because by giving an array you actually ask

    A[[3,1]] 
    

    Which gives the third and first index of the 2d array instead of the first index of the third index of the array as you want.

    You can use

     A[ind[0],ind[1]]
    

    You can also use (if you want more indexes at the same time);

    A[indx,indy]
    

    Where indx and indy are numpy arrays of indexes for the first and second dimension accordingly.

    See here for all possible indexing methods for numpy arrays: http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html

    0 讨论(0)
  • 2021-01-18 02:55

    Just use a tuple:

    >>> A[(3, 1)]
    8
    >>> A[tuple(ind)]
    8
    

    The A[] actually calls the special method __getitem__:

    >>> A.__getitem__((3, 1))
    8
    

    and using a comma creates a tuple:

    >>> 3, 1
    (3, 1)
    

    Putting these two basic Python principles together solves your problem.

    You can store your index in a tuple in the first place, if you don't need NumPy array features for it.

    0 讨论(0)
提交回复
热议问题