2017-06-01 55 views
1

獲得從元組位置矩陣(np.ndarray)我有一些零隨機值成從np.where

x=np.array([[1,2,3,0],[4,0,5,0],[7,0,0,0],[0,9,8,0]]) 
>>> x 
array([[1, 2, 3, 0], 
     [4, 0, 5, 0], 
     [7, 0, 0, 0], 
     [0, 9, 8, 0]]) 

矩陣而想要隨機值成僅是不爲零的位置。我可以從np.where

pos = np.where(x!=0) 
>>> (array([0, 0, 0, 1, 1, 2, 3, 3], dtype=int64), array([0, 1, 2, 0, 2, 0, 1, 2], dtype=int64)) 

得到(行,列)位置的元組是否有用於從pos位置矩陣xnp.random(或別的東西),只有在不改變其中爲零的方式嗎?

# pseudocode 
new_x = np.rand(x, at pos) 
+0

那麼您可以使用非零()方法來查找所有非零索引!結帳答案中的細節! – DexJ

回答

1

也可以使用x.nonzero(),它爲您提供了數組中的所有指標與非零值

,然後,你只需要把隨機值這些索引

nz_indices = x.nonzero() 
for i,j in zip(nz_indices[0],nz_indices[1]): 
    x[i][j] = np.random.randint(1500) #random number till 1500 

you can find more about randint() here >> randint docs

2

我假設你想用隨機整數取代非零值。

您可以使用numpy.placenumpy.random.randint函數的組合。

>>> x=np.array([[1,2,3,0],[4,0,5,0],[7,0,0,0],[0,9,8,0]]) 
>>> x 
array([[1, 2, 3, 0], 
     [4, 0, 5, 0], 
     [7, 0, 0, 0], 
     [0, 9, 8, 0]]) 
>>> lower_bound, upper_bound = 1, 5 # random function boundary 
>>> np.place(x, x!=0, np.random.randint(lower_bound, upper_bound, np.count_nonzero(x))) 
>>> x 
array([[2, 2, 3, 0], 
     [1, 0, 3, 0], 
     [2, 0, 0, 0], 
     [0, 4, 3, 0]]) 
+0

我認爲'mask = x!= 0'的簡單存儲,然後用它來生成和分配可能會更好。 – Divakar

+0

@Divakar沒錯,使用面膜更簡單。但是,在這種情況下,我更願意使用可用的函數(numpy.place)來處理這個特定的問題。 – lguiel

+0

但是我認爲這個函數的開銷會比較慢。 – Divakar

1

如何像這樣簡單的東西:

import numpy as np 
x = np.array([[1, 2, 3, 0], [4, 0, 5, 0], [7, 0, 0, 0], [0, 9, 8, 0]]) 
w = x != 0 
x[w] = np.random.randint(10, size=x.shape)[w] 
print(x) 

[[2 2 2 0] 
[0 0 4 0] 
[1 0 0 0] 
[0 3 1 0]] 
1

你也可以做

x = np.random.randint(1, 10, size=x.shape) * (x != 0) 
1

只是指數與np.nonzero

i = np.nonzero(x) 
x[i] = np.random.randint(1, 10, i[0].size) 

注意參考的是np.nonzero(x) < =>np.where(x) < =>np.where(x != 0)

+0

這返回'TypeError:列表索引必須是整數,而不是元組' – Jan

+0

是'x'而不是一個numpy數組的列表嗎?在你的問題中,它是一個數組。 –

+0

對不起。你是對的。測試時我錯誤地創建了我的陣列。它現在可以工作了。 – Jan