Home > OS >  How to compare two numpy arrays with multiple condition
How to compare two numpy arrays with multiple condition

Time:03-11

I have 2 NumPy arrays like the below

array_1 = np.array([1.2, 2.3, -1.0, -0.5]) 
array_2 = np.array([-0.5, 1.3, 2.5, -0.9]) 

We can do the element-wise simple arithmetic calculation (addition, subtraction, division etc) easily using different np functions

array_sum = np.add(array_1, array_2)
print(array_sum) # [ 0.7  3.6  3.5 -0.4]  

array_sign = np.sign(array_1 * array_2)
print(array_sign) # [-1.  1.  1. -1.]

However, I need to check element-wise multiple conditions for 2 arrays and want to save them in 2 new arrays (say X and Y).

For example, if both elements contain different sign (e.g.: 1st and 3rd element pairs of the given example)) then, X will contain 0 and Y will be the sum of the poitive element and abs(negative element)

X = [0]
Y = [1.7]

When both elements are positive (e.g.: 2nd element pair of the given example) then, X will contain the lower value and Y will contain the greater value

X = [1.3]
Y = [2.3]

If both elements are negative, then, X will be 0 and Y will be the sum of the abs(negative element) and abs(negative element)

So, the final X and Y will be something like

X = [0, 1.3, 0, 0]
Y = [1.7, 2.3, 3.5, 1.4]

I have gone through some posts (this, and this) that described, the comparison procedures between 2 arrays, but not getting idea for multiple conditions. Here, 2 arrays are very small but, my real arrays are very large (e.g.: contains 2097152 element per array).

Any ideas are highly appreciated.

CodePudding user response:

Try with numpy.select:

conditions = [(array_1>0)&(array_2>0), (array_1<0)&(array_2<0)]
choiceX = [np.minimum(array_1, array_2), np.zeros(len(array_1))]
choiceY = [np.maximum(array_1, array_2), -np.add(array_1,array_2)]

X = np.select(conditions, choiceX)
Y = np.select(conditions, choiceY, np.add(np.abs(array_1), np.abs(array_2)))

>>> X
array([0. , 1.3, 0. , 0. ])

>>> Y
array([1.7, 2.3, 3.5, 1.4])

CodePudding user response:

This will do it. It does require vertically stacking the two arrays. I'm sure someone will pipe up if there is a more efficient solution.

import numpy as np

array_1 = np.array([1.2, 2.3, -1.0, -0.5]) 
array_2 = np.array([-0.5, 1.3, 2.5, -0.9]) 

def pick(t):
    if t[0] < 0 or t[1] < 0:
        return (0,abs(t[0]) abs(t[1]))
    return (t.min(), t.max())

print( np.apply_along_axis( pick, 0, np.vstack((array_1,array_2))))

Output:

[[0.  1.3 0.  0. ]
 [1.7 2.3 3.5 1.4]]

The second line of the function can also be written:

        return (0,np.abs(t).sum())

But since these will only be two-element arrays, I doubt that saves anything at all.

  • Related