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

how to set nan values to numpy array with multiple condition

I have numpy array with some values.I want the points with value 2,3 and 7 will remain same but others value will be nan.

original nympy array looks like this

  [[0, 7, 2, ..., 1, 6, 0],
   [5, 3, 0, ..., 2, 5, 0],
   ...,
   [8, 2, 0, ..., 1, 0, 7],
   [0, 3, 2, ..., 0, 2, 0],
   [7, 1, 0, ..., 0, 7, 0]],

my expected result 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

  [[nan, 7, 2, ..., nan, nan, nan],
   [nan, 3, nan, ..., 2, nan, nan],
   ...,
   [nan, 2, nan, ..., nan, nan, 7],
   [nan, 3, 2, ...,   nan, 2, nan],
   [7, nan, nan, ..., nan, 7, nan]],

>Solution :

Combine np.isin and np.where:

a = np.array([[0, 7, 2, 1, 6, 0],
              [5, 3, 0, 2, 5, 0],
              [8, 2, 0, 1, 0, 7],
              [0, 3, 2, 0, 2, 0],
              [7, 1, 0, 0, 7, 0]],)

out = np.where(np.isin(a, [2, 3, 7]), a, np.nan)

If a had a float dtype, you can also modify in place:

a = np.array([[0, 7, 2, 1, 6, 0],
              [5, 3, 0, 2, 5, 0],
              [8, 2, 0, 1, 0, 7],
              [0, 3, 2, 0, 2, 0],
              [7, 1, 0, 0, 7, 0]], dtype=float)

a[~np.isin(a, [2, 3, 7])] = np.nan

Output:

array([[nan,  7.,  2., nan, nan, nan],
       [nan,  3., nan,  2., nan, nan],
       [nan,  2., nan, nan, nan,  7.],
       [nan,  3.,  2., nan,  2., nan],
       [ 7., nan, nan, nan,  7., nan]])
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