0

How can I get an array of indexes from a slice of a 2d numpy array? For example:

array = np.arange(20).reshape(5,4)
section = array[1:,1:]

section.shape is (4, 3). I want an array indexes of dimensions (2, 4, 3), with the first axis being the indexes of each value from section in array.

indexes should look like:

array([[[1, 1, 1],
        [2, 2, 2],
        [3, 3, 3],
        [4, 4, 4]], 

       [[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]]])

The indexes are needed so that I can modify it, then index array with array[indexes[0], indexes[1]].

I think this could be solved by slicing np.mgrid... but I'm not sure how this would be done. Or is there a better solution?

1 Answer 1

1

Using np.mgrid:

>>> i,j = array.shape
>>> np.mgrid[1:i,1:j]
array([[[1, 1, 1],
        [2, 2, 2],
        [3, 3, 3],
        [4, 4, 4]],

       [[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.