Printing locations of non-zero elements of an array in Python

Question:

I have an array y. I am identifying all nonzero elements with np.nonzero().

But, I want to print the output in a way as shown in the expected output.

import numpy as np

y=np.array([[ 0.0, -1.3e-08, 0.0 ],
            [-1.3e-08,  0.0, 1.4e-9],
            [0.0, 2.3e-7, 1.9e-6]])

Result=np.nonzero(y)
print(Result)

The current output is:

(array([0, 1, 1, 2, 2], dtype=int64), array([1, 0, 2, 1, 2], dtype=int64))

The expected output is:

array([[0,1],[1,0],[1,2],[2,1],[2,2]])
Asked By: rajunarlikar123

||

Answers:

You could use np.stack

import numpy as np

y=np.array([[ 0.0, -1.3e-08, 0.0 ],
            [-1.3e-08,  0.0, 1.4e-9],
            [0.0, 2.3e-7, 1.9e-6]])

Result=np.nonzero(y)
np.stack(Result, axis = -1)

Output

array([[0, 1],
       [1, 0],
       [1, 2],
       [2, 1],
       [2, 2]])
Answered By: delirium78
import numpy as np

y=np.array([[ 0.0, -1.3e-08, 0.0 ],
            [-1.3e-08,  0.0, 1.4e-9],
            [0.0, 2.3e-7, 1.9e-6]])

Result=np.nonzero(y)

print(np.array([[x,y] for x,y in zip(Result[0],Result[1])]))
Answered By: God Is One
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.