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

Extracting positive elements with indices in Python

I have a matrix, N. I would like to extract positive elements with their indices. The desired output is attached.

import numpy as np
from numpy import nan

N=np.array([[            nan,  9.65984145e-08,             nan,
                    nan,             nan,             nan,
                    nan],
       [-6.35107511e-09,             nan,  4.88443157e-09,
                    nan,  1.46664353e-09,             nan,
                    nan],
       [            nan, -1.38022162e-08,             nan,
         1.37404097e-08,             nan,  6.18065590e-11,
                    nan],
       [            nan,             nan, -7.82145993e-10,
                    nan,             nan,             nan,
         7.82145990e-10],
       [            nan, -3.98567193e-09,             nan,
                    nan,             nan,  3.98567195e-09,
                    nan],
       [            nan,             nan, -5.47197743e-11,
                    nan, -3.66918072e-09,             nan,
         3.72390048e-09],
       [            nan,             nan,             nan,
        -3.39767791e-09,             nan, -1.04008985e-09,
                    nan]])

The desired output is

(0,1) - 9.65984145e-08 
(1,2) - 4.88443157e-09 
(1,4) - 1.46664353e-09 and so on

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

>Solution :

If we need them separately in two separate arrays, we can get values by Boolean mask N >= 0 and then by transposing np.where array as:

values = N[N >= 0]
# [9.65984145e-08 4.88443157e-09 1.46664353e-09 1.37404097e-08 6.18065590e-11 7.82145990e-10 3.98567195e-09 3.72390048e-09]

indices = np.array(np.where(N >= 0)).T
# [[0 1]
#  [1 2]
#  [1 4]
#  [2 3]
#  [2 5]
#  [3 6]
#  [4 5]
#  [5 6]]
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