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

标签 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 bool 值,因为我使用了比较/检查运算符。我无法将其设置为值 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

最佳答案

您可以从映射到 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 出现在边缘,您可能会选择“脱离网格”的项目,这将导致错误)。

关于python - 引用数组的条件随机元素并替换它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29168646/

相关文章:

c++ - 从 C++ 中的函数返回二维数组

Python:如何绕 z 轴旋转曲面并绘制 3d 图?

python - 了解 Python 中的嵌套列表

python - 如何在 python 中将毫秒更改为秒?

c - 总线错误 :10 when try to reverse string in c

python - Numpy,数组没有自己的数据?

python - 如何在 PySide 中获取 QProcess 运行的命令的输出?

java - 从 txt 文件中读取整数并存储到数组中

python - 如何缩放基于 FFT 的互相关,使其峰值等于 Pearson's rho

python - 使用 scipy.interpolate.RegularGridInterpolator 出现错误 "There are 100 point arrays, but values has 2 dimensions"