2017-10-13 169 views
0

隨機位置我有一個隨機與零和填充的numpy的矩陣:選擇在numpy的矩陣

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

現在我需要挑選這個矩陣中的隨機位置,並把它轉化爲2

我試過了:

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

但是後來我得到一整行充滿了2s。我如何挑選一個隨機位置?謝謝

+3

選擇任一隨機位置或隨機位置,這也是1或任何隨機位置,這也是0?對於前者,只需執行:'np.put(grid,np.random.choice(grid.size),2)'。 – Divakar

+0

任何隨機位置。你的解決方案有效謝謝。 – nattys

回答

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 
+0

您的解決方案幫助我解決了我的代碼中的另一個問題,我不知道它與缺少索引有關。非常感謝 – nattys