We have two points in Cartesian space as origins and some other typical points. For typical points we are only interested in their distance from the origins: two numbers. so we want reach from df
JavaScript
x
8
1
d = {'origin1': [(1,0,0), (0,0,0)],
2
'origin2': [(2,0,0), (0,0,1)],
3
'point1': [(40,0,0), (0,0,20)],
4
'point2': [(50,0,0), (0,0,25)],
5
'point3': [(60,0,0), (0,0,30)]}
6
7
display(pd.DataFrame(data=d, index=[0, 1]))
8
to df
JavaScript
1
8
1
d = {'origin1': [(1,0,0), (0,0,0)],
2
'origin2': [(2,0,0), (0,0,1)],
3
'point1': [(39,38), (20,19)],
4
'point2': [(49,48), (25,24)],
5
'point3': [(59,58), (30,29)]}
6
7
display(pd.DataFrame(data=d, index=[0, 1]))
8
Of course here we chose simple number for simple distance to see the problem. in general case we should use Pythagorean distance formula.
Advertisement
Answer
It’s a solution for arbitrary dimensions of points & number of origins that we may have:
JavaScript
1
9
1
d = {'origin1': [(1,0,0) , (0,0,0 )],
2
'origin2': [(2,0,0) , (0,0,1 )],
3
'point1' : [(40,0,0), (0,0,20)],
4
'point2' : [(50,0,0), (0,0,25)],
5
'point3' : [(60,0,0), (0,0,30)]}
6
7
df_pnt = pd.DataFrame(data=d, index=[0, 1])
8
df_pnt
9
First we define some functions:
JavaScript
1
30
30
1
import pandas as pd
2
3
def distance(p1, p2):
4
'''
5
Calculate the distance between two given points
6
Arguments:
7
p1, p2: points
8
Returns:
9
Distance of points
10
'''
11
dmn = min(len(p1), len(p2))
12
vct = ((p1[i] - p2[i])**2 for i in range(dmn))
13
smm = sum(vct)
14
dst = smm**.5
15
return dst
16
17
def distances(df, n):
18
'''
19
Calculate the distances between points & origins
20
Arguments:
21
df: dataframe of points including origins
22
n : number of origins
23
Returns:
24
dataframe of distances
25
'''
26
df_dst = df.iloc[:, :n]
27
for column in df.columns[n:]:
28
df_dst[column] = df.apply(lambda row: tuple(distance(row[origin], row[column]) for origin in df.columns[:n]), axis=1)
29
return df_dst
30
Now this script gives your desired output:
JavaScript
1
2
1
distances(df_pnt, 2)
2
I hope it be what you want.