Jasper Bernales Jasper Bernales - 1 month ago 4
Python Question

Find Indices Of Columns Having Some Nonzero Element In A 2d array

I have a numpy array with dim (157,1944).

I want to get all unique indices for each row that has Nonzero element.

example: [[0,0,3,4], [0,0,1,1]] ----> [2,3]

If you look each row, there is a Non Zero element on position [2, 3]

So if I have

[[0,1,3,4], [0,0,1,1]]

i should get [1,2,3] because index 0 has no Nonzero element for all row

Answer

Not sure if your question is completely defined. However, say we start with

import numpy as np
a = np.array([[0,0,3,4], [0,0,1,1]])

then

>>> np.nonzero(np.all(a != 0, axis=0))[0]
array([2, 3])

are the indices of the columns for which none of the rows are nonzero, and

>>> np.nonzero(np.any(a != 0, axis=0))[0]
array([2, 3])

are the indices of the columns for which not all of the rows are zero (it happens to be the same for the example you gave).