选择在numpy的矩阵
问题描述:
随机位置我有一个随机与零和填充的numpy的矩阵:选择在numpy的矩阵
grid = np.random.binomial(1, 0.2, size = (3,3))
现在我需要挑选这个矩阵中的随机位置,并把它转化为2
我试过了:
pos = int(np.random.randint(0,len(grid),1))
但是后来我得到一整行充满了2s。我如何挑选一个随机位置?谢谢
答
你的代码的问题是,你只需要索引而不是两个随机数(随机)只有一个随机值。实现目标的方法之一:
# Here is your grid
grid = np.random.binomial(1, 0.2, size=(3,3))
# Request two random integers between 0 and 3 (exclusive)
indices = np.random.randint(0, high=3, size=2)
# Extract the row and column indices
i = indices[0]
j = indices[1]
# Put 2 at the random position
grid[i,j] = 2
+0
您的解决方案帮助我解决了我的代码中的另一个问题,我不知道它与缺少索引有关。非常感谢 – nattys
选择任一随机位置或随机位置,这也是1或任何随机位置,这也是0?对于前者,只需执行:'np.put(grid,np.random.choice(grid.size),2)'。 – Divakar
任何随机位置。你的解决方案有效谢谢。 – nattys