Suppose I am working with numpy in Python and I have a two-dimensional array of arbitrary size. For convenience, let\'s say I have a 5 x 5 array. The specific numbers are n
After playing around with various methods for a while, I just came to a fairly simple solution that works using ndarray.take
. Using the example I provided in the question:
a.take(range(-1,2),mode='wrap', axis=0).take(range(-1,2),mode='wrap',axis=1)
Provides the desired output of
[[24 20 21]
[4 0 1]
[9 5 6]]
It turns out to be a lot simpler than I thought it would be. This solution also works if you reverse the two axes.
This is similar to the previous answers I've seen using take
, but I haven't seen anyone explain how it'd be used with a 2D array before, so I'm posting this in the hopes it helps someone with the same question in the future.