Corresponding identifiers between Pandas DataFrames and the function used

I have two data frames that look like this:

df_A:

ID    x     y
a     0     0
c     3     2
b     2     5

df_B:

ID    x     y
a     2     1
c     3     5
b     1     2

I want to add a column to db_B, which is the Euclidean distance between x, y coordinates in df_B from df_A for each identifier. Desired Result:

ID    x     y    dist
a     2     1    1.732
c     3     5    3
b     1     2    3.162

Identifiers will not necessarily be in the same order. I know how to do this by going through the df_A lines and finding the corresponding identifier in df_B, but I was hoping to avoid using a for loop, as this will be used for data with tens of millions of lines. Is there a way to use the application, but on condition that it matches the identifiers?

+4
3

ID , .

df_B.set_index('ID', inplace=True)
df_A.set_index('ID', inplace=True)

df_B['dist'] = ((df_A - df_B) ** 2).sum(1) ** .5

, .

+4

, sklearn.metrics.pairwise.paired_distances:

In [73]: A
Out[73]:
    x  y
ID
a   0  0
c   3  2
b   2  5

In [74]: B
Out[74]:
    x  y
ID
a   2  1
c   3  5
b   1  2

In [75]: from sklearn.metrics.pairwise import paired_distances

In [76]: B['dist'] = paired_distances(B, A)

In [77]: B
Out[77]:
    x  y      dist
ID
a   2  1  2.236068
c   3  5  3.000000
b   1  2  3.162278
+3

NumPy , np.einsum .

, -

# Get sorted row indices for dataframe-A
sidx = df_A.index.argsort()
idx = sidx[df_A.index.searchsorted(df_B.index,sorter=sidx)]

# Sort A rows accordingly and get the elementwise differences against B
s = df_A.values[idx] - df_B.values

# Use einsum to square and sum each row and finally sqrt for distances
df_B['dist'] = np.sqrt(np.einsum('ij,ij->i',s,s))

, -

In [121]: df_A
Out[121]: 
   0  1
a  0  0
c  3  2
b  2  5

In [122]: df_B
Out[122]: 
   0  1
c  3  5
a  2  1
b  1  2

In [124]: df_B  # After code run
Out[124]: 
   0  1      dist
c  3  5  3.000000
a  2  1  2.236068
b  1  2  3.162278

runtime test einsum .

+1

Source: https://habr.com/ru/post/1664796/


All Articles