引用数组的条件随机元素并替换它

时间:2015-03-20 14:16:08

标签: python arrays numpy random

这是关于StackOverflow的第二个问题,与Python / Numpy中的编码有关。

我觉得肯定有某种函数可以执行伪代码:

np.random.choice([a[i-1,j],a[i+1,j],a[i,j-1],a[i,j+1]])==0 = 9

基本上,我希望随机函数选择一个与我相邻的单元格(向上,向下,向左,向右),值为0,并用9替换所述单元格

不幸的是,我知道为什么输入的代码是非法的。该语句的前半部分返回一个True / False布尔值,因为我使用了比较/检查运算符。我无法将其设置为值9。

如果我将代码加载分成两个代码并使用带有random.choice的if语句(查看等于零的相邻元素),那么在此之后,我需要某种函数或定义来回忆哪个单元格(向上向下或向右)执行随机生成器最初选择,然后我可以将其设置为9。

亲切的问候,

编辑:我也可以附上一个示例代码,这样你就可以运行它(我包含了我的错误)

a = np.empty((6,6,))
a[:] = 0
a[2,3]=a[3,3]=a[2,4] = 1

for (i,j), value in np.ndenumerate(a):
     if a[i,j]==1:
          np.random.choice([a[i-1,j],a[i+1,j],a[i,j-1],a[i,j+1]])==0 = 9

2 个答案:

答案 0 :(得分:1)

您可以从一系列方向(上,下,左,右)中进行选择,这些方向映射到2D阵列中的特定坐标移动,如下所示:

# generate a dataset
a = np.zeros((6,6))
a[2,3]=a[3,3]=a[2,4] = 1

# map directions to coordinate movements
nesw_map = {'left': [-1, 0], 'top': [0, 1], 'right': [1,0], 'bottom': [0,-1]}
directions = nesw_map.keys()

# select only those places where a == 1
for col_ind, row_ind in zip(*np.where(a == 1)):  # more efficient than iterating over the entire array
    x = np.random.choice(directions)
    elm_coords = col_ind + nesw_map[x][0], row_ind + nesw_map[x][1]
    if a[elm_coords] == 0:
        a[elm_coords] = 9

请注意,这不会执行任何类型的边界检查(因此,如果边缘出现1,您可以选择一个项目"关闭网格"这将导致错误)

答案 1 :(得分:0)

这是获得所需内容的最“基本”方式(添加try/except语句提供错误检查,因此您可以防止任何不需要的错误):

import random,numpy
a = numpy.empty((6,6,))
a[:] = 0
a[2,3]=a[3,3]=a[5,5] = 1

for (i,j), value in numpy.ndenumerate(a):
    var = 0
    if a[i,j]==1:
        while var==0:
            x=random.randrange(0,4)                   #Generate a random number
            try:      
                if x==0 and a[i-1,j]==0:              
                    a[i-1,j] =9                       #Do this if x = 0
                elif x==1 and a[i+1,j]==0:            
                    a[i+1,j] =9                       #Do this if x = 1
                elif x==2 and a[i,j-1]==0:             
                    a[i,j-1] =9                       #Do this if x = 2
                elif x==3 and a[i,j+1]==0:            
                    a[i,j+1] =9                       #Do this if x = 3
                var=1
            except:
                var=0

print a