Python numpy矩阵中随机位置的选择

Python numpy矩阵中随机位置的选择,python,numpy,matrix,random,Python,Numpy,Matrix,Random,我有一个随机填充了0和1的numpy矩阵: grid = np.random.binomial(1, 0.2, size = (3,3)) 现在我需要在这个矩阵中选择一个随机的位置,并将它变成2 我试过: pos = int(np.random.randint(0,len(grid),1)) 但是我得到了一整排2。如何仅选择一个随机位置?谢谢您的代码的问题是,您只需要为索引请求一个随机值,而不是两个随机数(随机)。这是实现目标的一种方法: # Here is your grid grid =

我有一个随机填充了0和1的numpy矩阵:

grid = np.random.binomial(1, 0.2, size = (3,3))
现在我需要在这个矩阵中选择一个随机的位置,并将它变成2

我试过:

pos = int(np.random.randint(0,len(grid),1))

但是我得到了一整排2。如何仅选择一个随机位置?谢谢

您的代码的问题是,您只需要为索引请求一个随机值,而不是两个随机数(随机)。这是实现目标的一种方法:

# 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   

代码的问题在于,您只需要为索引请求一个随机值,而不是两个随机数(random)。这是实现目标的一种方法:

# 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   

选择任意随机位置或任意同时为1的随机位置或任意同时为0的随机位置?对于前者,只需执行:
np.put(grid,np.random.choice(grid.size),2)
。任意随机位置。你的解决方案有效。谢谢。选择任意一个随机位置、任意一个也为1的随机位置或任意一个也为0的随机位置?对于前者,只需执行:
np.put(grid,np.random.choice(grid.size),2)
。任意随机位置。你的解决方案有效。谢谢。您的解决方案帮助我解决了代码中另一个我不知道与缺少索引有关的问题。非常感谢您。您的解决方案帮助我解决了代码中的另一个问题,我不知道这与缺少索引有关。多谢各位