Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(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]])

>Solution :

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]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading