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

quick way of filtering numpy array values

I’d like to filter a numpy array based on values from another array:

  • if the value from another array is positive, keep it untouched in this array,
  • if the value from another array is 0, change the value in this array to 0,
  • if the value from another array is negative, invert the sign of the value in this array,

currently I have:

import numpy as np
this = np.array([1, 2, -3, 4])
other = np.array([0, -5, -6, 7])

this[other == 0] = 0
this[other < 0] *= -1
print(this)
# [ 0 -2  3  4]

As shown, it needs to loop other twice to get the indices whose values are equal or smaller than 0, and it needs to loop this twice to change values. Is there a quicker way? (suppose this and other are very large arrays)

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 :

With np.sign function to get indication of the sign of numbers:

this * np.sign(other)

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