简体   繁体   English

在numpy矩阵中选择随机位置

[英]Selecting random position in numpy matrix

I have a numpy matrix that is randomly populated with zeros and ones: 我有一个用零和一随机填充的numpy矩阵:

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

Now I need to pick a random position inside this matrix and turn it to 2 现在我需要在此矩阵内选择一个随机位置并将其变为2

I tried: 我试过了:

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

But then I get an entire row filled with 2s. 但是然后我得到一整行充满2s。 How do I pick only one random position? 如何只选择一个随机位置? Thank you 谢谢

The issue with your code is that you're just requesting only one random value for the indices instead of two random numbers (random). 代码的问题在于,您只要求索引的一个随机值,而不是两个随机数(随机数)。 This one way of achieving your goal: 实现目标的一种方法:

# 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   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM