簡體   English   中英

Python:僅具有非零條目的數組中所有行的索引

[英]Python: Indices of all rows in array with non-zero entries only

在一個numpy數組中 ,如何找到僅具有非零條目的所有行索引 例如在數組中:

A = np.array([[ 1,  0,  5],
              [25,  2,  0],
              [ 7,  8,  9],
              [ 0,  0,  4],
              [11, 14, 15]])

我想將[2,4]作為輸出,因為第2行和第4行是所有條目均為非零的唯一行。

目前,我正在使用

B = A[np.all(A != 0, axis=1)]

獲取一個數組,其中所有具有至少一個零的行都將被丟棄。 但是我需要找到索引(即2和4)。

您的方法應該可以進行如下更改:

np.where(np.all(A != 0, axis=1))[0].tolist()
Out[284]: [2, 4]
In [1]: A = np.array([[ 1,  0,  5],
                      [25,  2,  0],
                      [ 7,  8,  9],
                      [ 0,  0,  4],
                      [11, 14, 15]])

In [2]: Indx1 = np.all(A != 0, axis=1) 
        print Indx1
Out[2]: Indx1 = [False False  True False  True] 

In [3]: Indx2 = np.where(Indx1==True)
        print Indx2
Out[3]: (array([2, 4]),)

In [4]: Indx = A[Indx2[0]]
        print Indx
Out[4]: [2 4]

暫無
暫無

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

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