在numpy矩阵中选择随机位置

时间:2017-10-13 16:51:39

标签: python numpy matrix random

我有一个随机填充零和一个的numpy矩阵:

grid = np.random.binomial(1, 0.2, size = (3,3))

现在我需要在此矩阵中选择一个随机位置并将其转换为2

我试过了:

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

然后我得到一整行充满2s。我如何只挑选一个随机位置?谢谢

1 个答案:

答案 0 :(得分: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