0

Lets say I have a numpy array:

arr = np.array([1,2,3,4,9,11])

and I would like to find elements of a target array say:

target = np.array([3,10])

that are closest to the elements of the original array. So the the results is going to be:

[3,3,3,3,10,10] Because 1,2,3,4 are matched to 3 of the target array and 9,11 were matched to 10.

Is there a function in scipy/numpy to do that?

2
  • No, there is no built-in function. You'll have to plan out your logical steps and post your code -- if you get stuck. Commented Apr 3, 2020 at 18:14
  • @motam79 accept an answer if you think it helped you. Commented Apr 5, 2020 at 11:28

2 Answers 2

1

There is no direct function just for that I think. This one-liner can do what you want.

First select the indices with minimum difference and take the values from target array.

arr = target[abs(arr[None, :] - target[:, None]).argmin(axis=0)]
Sign up to request clarification or add additional context in comments.

Comments

0
import numpy as np
ar = np.array([1,2,3,4,9,11])
tar = np.array([3,10])
def target(arr,target):
    ans=np.empty([len(arr)], dtype=int)
    for elem in range(arr.size):
        dist=[]
        for ele in range(target.size):
            dist.append(abs(target[ele]-arr[elem]))
        ans[elem]=target[dist.index(min(dist))]
    return ans

print(target(ar,tar))

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.