How to access values using multidimensional indices in numpy?

Viewed 77

I am having troubles accessing the value from the given indices:

indices = array([[[1, 1],
        [1, 2],
        [1, 3],
        [2, 1],
        [2, 2],
        [2, 3],
        [3, 1],
        [3, 2],
        [3, 3]],

       [[1, 2],
        [1, 3],
        [1, 4],
        [2, 2],
        [2, 3],
        [2, 4],
        [3, 2],
        [3, 3],
        [3, 4]],

       [[2, 1],
        [2, 2],
        [2, 3],
        [3, 1],
        [3, 2],
        [3, 3],
        [4, 1],
        [4, 2],
        [4, 3]],

       [[2, 2],
        [2, 3],
        [2, 4],
        [3, 2],
        [3, 3],
        [3, 4],
        [4, 2],
        [4, 3],
        [4, 4]]])

for an array:

padded_x = array([[0, 0, 0, 0],
       [0, 1, 1, 0],
       [0, 1, 1, 0],
       [0, 0, 0, 0]])

I tried accessing using result = padded_x[indices] but it returns result in shape (4, 9, 2, 4), I need it in shape (4,9). I do not want to use for loops as I am dealing very large arrays.

Context: The indices represent 3x3 neighbourhood indices at point [i,j]. To prevent the out of bounds array access, the original array has been padded (hence the name padded_x)

1 Answers

Numpy has some weird indexing rules, when you want to access multiple multi-dimensional indices.

You have to give a tuple containing an iterable for each dimension. So when you want to access (0, 0) and (2, 3) of padded_x, you'd have to write padded_x[([0, 2], [0, 3])].

For your example, it should be

indices = (
    [[-1, -1, -1, 0, 0, 0, 1, 1, 1],
     [-1, -1, -1, 0, 0, 0, 1, 1, 1],
     [0, 0, 0, 1, 1, 1, 2, 2, 2],
     [0, 0, 0, 1, 1, 1, 2, 2, 2]],
    [[-1, 0, 1, -1, 0, 1, -1, 0, 1],
     [0, 1, 2, 0, 1, 2, 0, 1, 2],
     [-1, 0, 1, -1, 0, 1, -1, 0, 1],
     [0, 1, 2, 0, 1, 2, 0, 1, 2]]
)

padded_x = np.array([[0, 0, 0, 0],
                     [0, 1, 1, 0],
                     [0, 1, 1, 0],
                     [0, 0, 0, 0]])

result = padded_x[indices]

Notice that the working index array can be created from the indices from your attempt by transposing: indices = tuple(indices.transpose((2, 0, 1))).

It has to be a tuple for numpy to regard it as multi-dimensional index! Otherwise it is regarded as a list of 1D indices.

Related