2

I have two numpy arrays: ones is some coordinates (x, y, z) with an id and another one is only some coordinates (x, y, z):

cord_id=np.array([[0.,0.,0.,8.],[0.,0.,10.,8.],[0.,0.,20.,8.],[0.,0.,30.,8.],\
                  [2.,1.,0.,9.],[2.,1.,10.,7.],[2.,1.,20.,7.],[2.,1.,30.,7.]])
cord_only=np.array([[0.,0.,.1],[0.,0.,20.1],[2.1,1.,0.],[2.,1.,11.1]])

I want to find out each point of cord_only is closer to which point of cord_id and then add the related id (last column of cord_id) to the point. For example, the first point of cord_only is closest to first point of cord_id, so I add 8. to it. Second point of cord_only is closest to third of cord_id, third is closest to fifth and fourth is also closet to sixth point. Finally, I want to get it as:

new_arr=np.array([[0.,0.,.1,8.],[0.,0.,20.1,8.],[2.1,1.,0.,9.],[2.,1.,11.1,7.]])

I tried the following code but could not find out the closet points:

from scipy.spatial import distance
cord_id[np.where(np.min(distance.cdist(cord_only, cord_id[:,:-1]),axis=0))]

i do appreciate any help in advance to do it in python.

1 Answer 1

2

using np.where(np.min(X)) doesn't give you the correct answer as min returns the minimum value (rather than the index of the minimum value) and where will return all nonzeros. I think what you are looking for is argmin:

from scipy.spatial import distance
ids = cord_id[np.argmin(distance.cdist(cord_only, cord_id[:,:-1]),axis=1)][:,-1]
new_arr = np.hstack([cord_only,ids.reshape(-1,1)])
Sign up to request clarification or add additional context in comments.

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.