如何从具有周期性边界条件的numpy数组中选择一个窗口? [英] How do I select a window from a numpy array with periodic boundary conditions?
本文介绍了如何从具有周期性边界条件的numpy数组中选择一个窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我像这样制作一个二维数组:
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]])
,并且我希望能够围绕任何给定的元素选择一个3x3的窗口,以便该窗口围绕边界包裹,我该怎么做呢?我知道如果窗口的边界不与原始数组的边界重叠,我可以做到这一点:
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]])
但是如果我使用像A[i-1:i+2,j-1:j+2]
这样的表达式,它只会为i = 0(例如j = 0)返回一个空数组.
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.
推荐答案
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]]
这篇关于如何从具有周期性边界条件的numpy数组中选择一个窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文