0

I have a dataframe that contains x-y coordinates for a series of objects over time. I am trying to work out the total path length of each of these objects. I know the equation to work out the length of a line it

(√((x2-x1))^2+(y2-y1))) + (√((x3 - x2))^2+(y3-y2)))...

How would I work out the length of each individuals objects path from the data frame?

Thanks in advance!

Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
Rory235
  • 1
  • 3

1 Answers1

0

I am unsure what exactly you mean by 'length of each individual object path'. If you want to add the distance between each 2 successive points in the dataframe, with the last point connecting to the first, use something like this:

import math

data = {"x": [0,2,6,4,0,3,6]
        "y": [0,4,2,3,4,1,7]
       }
df = pd.DataFrame(data)

points = list(df.to_records(index=False))
total_length = sum(math.hypot(p[i][0] - p[i-1][0], p[i][1] - p[i-1][1]) for i,_ in enumerate(p))
print(total_length)

If instead you would like to find a 2d convex hull (i.e. the minimum bounding polygon) for the set of 2d points, use scipy library for this. Try this code out:

from scipy.spatial import ConvexHull, convex_hull_plot_2d
points_arr = np.array([[x,y] for x,y in points])
hull = ConvexHull(points_arr)

import matplotlib.pyplot as plt
plt.plot(points_arr[:,0], points_arr[:,1], 'o')
hs = hull.simplices
for simplex in hull.simplices:
    plt.plot(points_arr[simplex, 0], points_arr[simplex, 1], 'k-')

total_length = sum(math.dist(hs[i], hs[i-1]) for i,_ in enumerate(hs))
print(total_length)
You_Donut
  • 155
  • 8