簡體   English   中英

如何在不使用循環的情況下用列/行索引替換 (0,1) numpy 數組的非零元素?

[英]How to replace non-zero elements of a (0,1) numpy array by it's column/ row indices without using a loop?

我有一個 0 和 1 的 numpy 數組。

def random_array(p):
    return np.random.choice(2, 6, p=[p, 1-p])
my_matrix = np.array([random_array(j) for j in np.random.uniform(0.3, 1.0, 4)])

我可以將所有零零元素的索引作為np.nonzero(my_matrix) 請您幫我將所有這些索引分配給它所在的列號(即使列索引也可以,我們從 0 而不是 1 開始)。 例如,

array([[0, 2, 0, 4, 5, 6],
       [0, 0, 0, 4, 5, 0],
       [1, 2, 0, 4, 0, 0],
       [0, 2, 3, 4, 5, 6]])

在這里,所有的 1 都被替換為列號。 因此,這是一個所有非零元素都是 1 的矩陣。如果你能找到列的索引,那么它也將是 fibulas,因為我可以通過加 1 得到相同的結果。

注意:我不希望為此任務使用任何循環。

您可以將數組與包含相應行/列索引的另一個相同大小的數組相乘:

## Dummy data
#  Array size
s = (6,4)
#  Axis along which we need to calculate the index:
a = 0
#  Random binary array
x = np.random.rand(*s).round()

#  Get the index along one axis using broadcasting (starting with 1)
x = x*(np.expand_dims(range(s[a]),len(s)-a-1)+1)

如果我理解得很好,您想用它們的列索引(從 1 而不是 0 開始)替換所有非零元素,對嗎? 然后你可以這樣做:

idx = np.nonzero(my_matrix)
my_matrix[idx[0], idx[1]] = idx[1]+1
In [169]: def random_array(p):
     ...:     return np.random.choice(2, 6, p=[p, 1-p])
     ...: my_matrix = np.array([random_array(j) for j in np.random.uniform(0.3, 1.0, 4)])
In [170]: my_matrix
Out[170]: 
array([[0, 0, 0, 0, 0, 0],
       [0, 1, 1, 0, 0, 0],
       [0, 0, 1, 1, 0, 1],
       [1, 1, 0, 0, 1, 0]])

只需乘以范圍索引。 通過廣播 (6,) arange 適用於列:

In [171]: np.arange(1,7)*my_matrix
Out[171]: 
array([[0, 0, 0, 0, 0, 0],
       [0, 2, 3, 0, 0, 0],
       [0, 0, 3, 4, 0, 6],
       [1, 2, 0, 0, 5, 0]])

對於行

In [172]: np.arange(1,5)[:,None]*my_matrix
Out[172]: 
array([[0, 0, 0, 0, 0, 0],
       [0, 2, 2, 0, 0, 0],
       [0, 0, 3, 3, 0, 3],
       [4, 4, 0, 0, 4, 0]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM