How to access numpy array with a set of indices stored in another numpy array?



  • I have a numpy array which stores a set of indices I need to access another numpy array.

    I tried to use a for loop but it doesn't work as I expected.

    The situation is like this:

    >>> a
    array([[1, 2],
           [3, 4]])
    >>> c
    array([[0, 0],
           [0, 1]])
    >>> a[c[0]]
    array([[1, 2],
           [1, 2]])
    >>> a[0,0]         # the result I want
    1
    
    

    Above is a simplified version of my actual code, where the c array is much larger so I have to use a for loop to get every index.

    Convert it to a tuple:

    >>> a[tuple(c[0])]
    1
    
    

    Because list and array indices trigger advanced indexing. tuples are (mostly) basic slicing.

    Index a with columns of c by passing the first column as row's index and second one as column index:

    In [23]: a[c[:,0], c[:,1]]
    Out[23]: array([1, 2])
    
    

    来自:https://stackoverflow.com/questions/41951140/how-to-access-numpy-array-with-a-set-of-indices-stored-in-another-numpy-array



最新帖子