简体   繁体   中英

How to find the closests points of two numpy arrays in python

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.

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)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM