Numpy array of multiple indices replace with a different matrix

前端 未结 2 1130
失恋的感觉
失恋的感觉 2021-01-21 19:26

I have an array of 2d indices.

indices = [[2,4], [6,77], [102,554]]

Now, I have a different 4-dimensional array, arr, and I want to only extrac

相关标签:
2条回答
  • 2021-01-21 20:16

    We need to index into the first two axes with the two columns from indices (thinking of it as an array).

    Thus, simply convert to array and index, like so -

    indices_arr = np.array(indices)
    out = arr[indices_arr[:,0], indices_arr[:,1]]
    

    Or we could extract those directly without converting to array and then index -

    d0,d1 = [i[0] for i in indices], [i[1] for i in indices]
    out = arr[d0,d1]
    

    Another way to extract the elements would be with conversion to tuple, like so -

    out = arr[tuple(indices_arr.T)]
    

    If indices is already an array, skip the conversion process and use indices in places where we had indices_arr.

    0 讨论(0)
  • 2021-01-21 20:19

    Try using the take function of numpy arrays. Your code should be something like:

    outputarray= np.take(arr,indices)
    
    0 讨论(0)
提交回复
热议问题