Abhishek Thakur
Abhishek Thakur

Reputation: 16995

select closest values from two different arrays

suppose i have a numpy array

A = [[1 2 3]
     [2 3 3]
     [1 2 3]]

and another array

B = [[3 2 3]
     [1 2 3]
     [4 6 3]]

and a array of true values:

C = [[1 4 3]
     [8 7 3]
     [4 10 3]]

Now I want to create an array D, the elements of which are dervied from either A or B, the condition being the closest value of each element from array C.

Is there any pythonic way to do this? Right now im using loops

Upvotes: 4

Views: 140

Answers (1)

roman
roman

Reputation: 117337

>>> K = abs(A - C) < abs(B - C)  # create array of bool
[[True, False, False],
 [True,  True, False],
 [False, False, False]]
>>> D = where(K, A, B)     # get elements of A and B respectively

Upvotes: 7

Related Questions