0

I would like to calculate the distance between data points in an array.

Example

A1 = array([[ 54.        ,  15.        ,   1.        ],
       [ 55.        ,  13.66311896,   1.        ],
       [ 56.        ,  10.16311896,   1.95491503],
       [ 57.        ,   5.83688104,   4.45491503],     # shape 6rows x 3 col
       [ 58.        ,   2.33688104,   7.54508497],
       [ 59.        ,   1.        ,  10.04508497],
       [ 60.        ,   1.        ,  11.        ],

Now, I want to calculate the distance between points in column 1 & column 2. and all the distance should be calculated from Row 0 ie.,(x1,y1 = 15,1) but x2,y2 is variable changing from elements row 1 to row6. And I want save this distance as a 'list'. Please help me in solving this in python

  • Please post your [example] here. If you tell us what you have tried so far and which errors or problems you are getting, it would be much easier for us to help you. – Muhammad Mohsin Khan Jan 17 '22 at 13:21
  • dist_matrix = ((A1.reshape(N_points_in_A1, 1, dim_of_point) - A2.reshape(1, N_points_in_A2, dim_of_points))**2).sum(2)**0.5. dist_matrix[i, j] will contain the distance of point i in A1 form point j in A2 – yann ziselman Jan 17 '22 at 13:26
  • Thanks for your comment @ yann . Could you please explain what is **dim_of_points** & **sum(2)** in `((A1.reshape(N_points_in_A1, 1, dim_of_point) - A2.reshape(1, N_points_in_A2, dim_of_points))**2).sum(2)**0.5. dist_matrix[i, j]` – Akhilesh Arkala Jan 17 '22 at 13:36
  • Does this answer your question? [How to do n-D distance and nearest neighbor calculations on numpy arrays](https://stackoverflow.com/questions/52366421/how-to-do-n-d-distance-and-nearest-neighbor-calculations-on-numpy-arrays) – Daniel F Jan 17 '22 at 13:53

1 Answers1

1

Pythagoras theorem states sqrt(a^2+b^2)=c where c is the distance between the tips of the orthogonal lines reaching point a and b.

import math
from math import sqrt
dist_list=[]
for i in A1[1:]:
    dist=sqrt(pow(A1[0][1]-i[1],2)+pow(A1[0][2]-i[2],2))
    dist_list.append(dist)

If you dont want to import math:

for i in A1[1:]:
    dist=pow(pow(A1[0][1]-i[1],2)+pow(A1[0][2]-i[2],2),0.5)
    dist_list2.append(dist)
Regretful
  • 336
  • 2
  • 10