Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

python - How do I select a window from a numpy array with periodic boundary conditions?

Suppose I make a 2d array like this:

>>> A=np.arange(16).reshape((4,4))
>>> A
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

and I want to be able to select a 3x3 window around any given element so that the window wraps around the boundaries how would I do that? I know I can do this if the boundaries of the window don't overlap the boundaries of the original array:

>>> A[1:4,0:3]
array([[ 4,  5,  6],
       [ 8,  9, 10],
       [12, 13, 14]])

but if I use an expression like A[i-1:i+2,j-1:j+2] it only returns an empty array for i=0, j=0 for example.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
import numpy as np

A=np.arange(16).reshape((4,4))

def neighbors(arr,x,y,n=3):
    ''' Given a 2D-array, returns an nxn array whose "center" element is arr[x,y]'''
    arr=np.roll(np.roll(arr,shift=-x+1,axis=0),shift=-y+1,axis=1)
    return arr[:n,:n]

print(A)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]
#  [12 13 14 15]]

print(neighbors(A,0,0))
# [[15 12 13]
#  [ 3  0  1]
#  [ 7  4  5]]

print(neighbors(A,1,0))
# [[ 3  0  1]
#  [ 7  4  5]
#  [11  8  9]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...