简体   繁体   中英

Distance between points in two data frames

I'm new to python and I tried searching but could not find a solution.

I have two dataframes with Cartesian coordinates.

node    x      y    value
abc    645    714   8 
def    187    754   11 

location  x    y    value
ijk      621  744   1 
lmn      202  720   -5  

I want to find the minimum distance of each location in df2 with nodes in df1 and update "value" in df1.

I have seen cdist to calculate the minimum distance, but how do I link that back to the corresponding? node

Since ijk is close to abc and lmn to def, the final answer should be

node    x      y    value
abc    645    714   9 
def    187    754   6

Here's a way to do it from scratch:

import numpy as np
import pandas as pd

df1 = pd.DataFrame({'node': ['abc', 'def'], 
                    'x': [645, 187], 
                    'y': [714, 754], 
                    'value': [8, 11]}) 
df2 = pd.DataFrame({'location': ['ijk', 'lmn'], 
                    'x': [621,  202], 
                    'y': [744, 720], 
                    'value': [1, -5]}) 

# compute Euclidean distances (using Pythagoras' theorem)
df2['distances'] = [[((df1['x'][j] - df2['x'][i]) ** 2 
                    + (df1['y'][j] - df2['y'][i]) ** 2) ** 0.5 
                     for j in range(len(df1))] 
                    for i in range(len(df2))]
df2
    location  x     y      value  distances
0   ijk       621   744     1     [38.41874542459709, 434.11519208615584]
1   lmn       202   720    -5     [443.0406301909566, 37.16180835212409]
df1['new_value'] = [df1['value'][row] + df2['value'][np.argmin(df2['distances'][row])] 
                    for row in range(len(df1))] 
df1
    node    x       y      value  new_value
0   abc     645     714     8     9
1   def     187     754    11     6

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