【问题标题】:Selecting random position in numpy matrix在numpy矩阵中选择随机位置
【发布时间】:2025-05-01 22:50:02
【问题描述】:

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

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

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

我试过了:

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

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

【问题讨论】:

  • 选择任意随机位置或任意同时为1的随机位置或任意随机位置也为0?对于前者,只需这样做:np.put(grid,np.random.choice(grid.size),2).
  • 任意随机位置。您的解决方案有效。谢谢。

标签: python numpy matrix random


【解决方案1】:

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

# 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   

【讨论】:

  • 您的解决方案帮助我解决了我的代码中另一个我不知道与缺少索引有关的问题。非常感谢