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)
>Solution :
With np.sign function to get indication of the sign of numbers:
this * np.sign(other)
array([ 0, -2, 3, 4])