我用 numpy 数组表示一个直立的方格(一个元素与上面的元素、下面的元素、右边和左边的元素连接,但不是对角线连接)。我需要从晶格中选择一个随机元素并将其值更改为随机相邻元素的值。有没有简单的方法可以做到这一点?
目前我最好的想法是从行和列索引中随机化,然后尝试元素是否有四个邻居,然后尝试左侧是否丢失,然后是右侧,然后是顶部,然后是底部,最后尝试四个角。这看起来确实很麻烦。我的数据是-1,+1随机分布在晶格中:
lattice=np.random.uniform(low=0.0, high=1.0, size=[30,30])
lattice[lattice<0.2]=-1
lattice[lattice>0.2]=1
假设随机元素是lattice[0,0]
,那么我期望返回的格子是
lattice[0,0]=np.random.choice([lattice[0,1], lattice[1,0]])
编辑:对于之前对复数的误导性使用,我深表歉意。
最佳答案
使用 scipy.ndimage.generic_filter将每个元素周围的 3x3 网格传递给我们选择的函数。该函数选择一个随机相邻元素。
边界(原始数组之外的值)设置为 nan,并且我们在函数中过滤掉 nan,因此我们只从有效元素中进行选择。
import numpy as np
import scipy.ndimage as ndimage
def random_function(arr, **kwargs):
from random import choice
mask = ~np.isnan(arr) & kwargs['mask']
return choice(arr[mask])
n = 5
array = np.arange(n ** 2).reshape((n, n))
cross_mask = np.zeros(9).astype(bool)
cross_mask[[1, 3, 5, 7]] = True
res = ndimage.generic_filter(array, random_function, size=3, mode='constant', cval=np.nan, extra_keywords={'mask': cross_mask})
print array
print res
结果:
array:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
res:
[[ 1 6 7 8 3]
[ 6 1 12 9 8]
[11 10 7 8 9]
[10 17 18 17 18]
[15 20 21 18 19]]
关于python - 从 numpy 数组中选择相邻元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22248457/