1

Assuming I have the following numpy 2d array where arr[2,0] = 7.

arr =
[[1 2 3]
 [4 5 6]
 [7 8 9]]

How can I achieve a wrapping effect such that when I try to retrieve arr[3,0] for example, I won't be getting a "index 3 is out of bounds for axis 0 with size 3" but will get arr[0,0] = 1 instead in return?

Thank you!

1 Answer 1

1

You can index one dimension at a time with with take:

In [72]: np.take(arr,3,0, mode='wrap')
Out[72]: array([1, 2, 3])
Sign up to request clarification or add additional context in comments.

3 Comments

Bad idea. numpy.take can't return a view. It needs to copy all selected data into a new buffer, which gets very expensive for large arrays.
@user2357112supportsMonica, take and put are the only buitin functions (that I know of) that have wrap option. Of course the OP could do their own index wrapping before performing the regular indexing.
@user2357112supportsMonica, np.take has favorable speeds compared to the equivalent advanced indexing, e.g. for arr.take([3,7,10],0,'wrap'). For scalar indexing your own wrapping is faster.

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.