Jill Clover
Jill Clover

Reputation: 2318

Return index of every non-zero element in array

I know there is a way to return the index of the maximum element in an array in python: numpy.argmax(). Is there a way to return index of every non-zero element?

For example

array([[ 0.,  1.,  1., ...,  1.,  0.,  0.],
       [ 0.,  1.,  1., ...,  1.,  0.,  1.],
       [ 0.,  1.,  1., ...,  1.,  0.,  0.],
       ..., 
       [ 0.,  1.,  1., ...,  1.,  0.,  0.],
       [ 0.,  1.,  1., ...,  1.,  0.,  0.],
       [ 0.,  1.,  1., ...,  1.,  0.,  0.]], dtype=float32)

to

[[1, 2, ...,6],
[1,2,...6,8],
...
...
]

Upvotes: 0

Views: 991

Answers (1)

antikantian
antikantian

Reputation: 620

Do you want something like this:

x = np.asarray([0, 1, 2, 3, 0, 1])
In [129]: np.nonzero(x)
Out[129]: (array([1, 2, 3, 5]),)

See: [1], [2], [3]

Upvotes: 2

Related Questions