2017-04-25 30 views
0

numpy数组中,如何找到只有非零条目的所有行的索引。例如,阵列中:Python:只有非零条目的数组中的所有行的索引

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)。

回答

1

你的方法应该以一点变化如下工作:

np.where(np.all(A != 0, axis=1))[0].tolist() 
Out[284]: [2, 4] 
0
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] 
相关问题