简体   繁体   中英

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

In a numpy array , how can I find the indices of all rows that have non-zero entries only . For example in the array:

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

I would like to have [2,4] as the output, since the rows 2 and 4 are the only rows where all entries are non-zero.

Presently, I am using

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

to get an array where all rows with at least one zero have been discarded. But I need to find the indices (ie 2 and 4).

Your method should work with a bit change as below:

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM