Wrap slice around edges of a 2D array in numpy

后端 未结 5 880
别跟我提以往
别跟我提以往 2020-12-15 12:00

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

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 12:44

    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.

提交回复
热议问题