0

I have two long lists of of X and Y coordinates in space. I would like to calculate the absolute change in total distance in each frame. Everywhere I look online it is only the Euclidian distance for the entire list which isn't what I am trying to get. Sample data below

Sample Data

I tried to calculate Euclidian distance with a for loop but I am not sure if i need to be nested. this is what I have as so far:

import pandas as pd
import numpy as np

data = pd.read_csv("/Users/ryan/Desktop/blahblah/Documents/Python_input.csv")
X_cords = data['X'].tolist()
Y_cords = data['Y'].tolist()
Z_cords = data['Z'].tolist()

X_cords1 = np.array(X_cords)
Y_cords1 = np.array(Y_cords)
Z_cords1 = np.array(Z_cords)
Robert
  • 7,394
  • 40
  • 45
  • 64
  • 1
    Please provide the input as a reproducible DataFrame constructor and also provide the matching expected output. – mozway Nov 02 '22 at 20:40
  • So you mean the pair-wise distance between each `x` and `y` value in a row? – Hefe Nov 02 '22 at 20:50
  • How about this https://stackoverflow.com/a/69877448/15975987 – Hefe Nov 02 '22 at 20:53
  • What do you mean by "the absolute change in total distance in each frame"? – Yuri Ginsburg Nov 02 '22 at 20:58
  • Where are there two lists? Do want the total distance traveled from coord 0 to coord 11, or are you looking for the total difference between THIS set of coordinates and some other set of coordinates? – Tim Roberts Nov 02 '22 at 20:59
  • @TimRoberts I assumed he meant `x` is one list and `y` is the other – Hefe Nov 02 '22 at 21:01
  • @Hefe -- That doesn't make sense. He said these are X,Y coordinates in space. In other words, that's ONE list. – Tim Roberts Nov 02 '22 at 21:11

1 Answers1

0

Assuming you want the Euclidean distance between the successive points, you can compute:

d = sqrt((x2-x1)**2 + (y2-y1)**2)

Which translates into:

import numpy as np

df['distance'] = np.sqrt(df['x'].diff().pow(2)
                         .add(df['y'].diff().pow(2)))

print(df)

Output:

             x           y  distance
0   572.744068  440.704134       NaN
1   573.575947  441.776790  1.357429
2   573.013817  439.213108  2.624586
3   572.724416  439.261388  0.293400
4   572.118274  439.060655  0.638515
5   573.229471  441.497860  2.678567
6   572.187936  441.334470  1.054272
7   574.458865  441.610036  2.287587
8   574.818314  441.935855  0.485140
9   571.917208  441.397476  2.950639
10  573.958625  440.384438  2.278954
11  572.644475  441.341588  1.625770

Reproducible example input:

np.random.seed(0)
df = pd.DataFrame({'x': np.random.uniform(570, 575, size=12),
                   'y': np.random.uniform(439, 442, size=12)})

variant for an arbitrary number of dimensions:

# here in 3D 
df['distance'] = np.sqrt(df[['x', 'y', 'z']].diff().pow(2).sum(
axis=1))
mozway
  • 194,879
  • 13
  • 39
  • 75