Search code examples
pythonpython-3.xnumpyelementwise-operations

Numpy given two arrays with values and confidence create an array of highest confidence values


I want to pick the values from highest confidence model elementwise

vals1 = np.array( [0, 0, 11, 12, 0, 0, 13, 14]) # predicted values using method 1
probs1 = np.array([0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2]) # predicted values using method 1
vals2 = np.array( [0, 21, 0, 22, 0, 23, 0, 24]) # predicted values using method 2
probs2 = np.array([0.1, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, 0.9]) # predicted values using method 2

# Desired result : [0, 0, 11, 12, 0, 23, 0, 24]

I can to it elementwise in a loop:

result = np.zeros(vals1.shape[0])
for i in range(vals1.shape[0]):
    result[i] = vals1[i] if probs1[i] > probs2[i] else vals2[i]
return result

What is the right numpy way to select elements like this?


Solution

  • As @HansHirse mentioned in the comments:

    np.where(probs1 > probs2, vals1, vals2)
    

    which for each element, checks the condition and if it is True returns corresponding element of vals1, otherwise vals2.