Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

python - [pandas]Is there anyway to calculate cumulative travel distance faster or simpler

I am trying to speed up my code.

Here is my sample code. (The actual code is more complex

import pandas as pd
import time, math, random

length=10000
x = [random.randint(0,100) for _ in range(length)]
y = [random.randint(0,100) for _ in range(length)]
x_pd = pd.Series(data=x)
y_pd = pd.Series(data=y)
print(x)
print(y)
print(x_pd)
print(y_pd)

distance= 0
distance2= 0
t = time.time()
for k in range(1, len(x)):
    distance += math.sqrt((x[k] - x[k-1])**2 + (y[k] - y[k-1])**2)
print("dist from list : %lf"% distance)
print("duration for compute moving distance = ", time.time()-t)
            
# compute by rolling
t = time.time()
for k in range(1, len(x_pd)):
    distance2 += math.sqrt((x_pd[k] - x_pd[k-1])**2 + (y_pd[k] - y_pd[k-1])**2)
print("dist from pd.Series : %lf"% distance2)
print("duration for compute moving distance = ", time.time()-t)

As you see above, I have 2 list(or pandas series) and these are X, Y pose list. i want to calculate cumulative travel distance.

I think if length is larger, calculate using pandas like above is more slow due to for iteration.

Is there anyway to calculate faster or simpler than i thought? thank you!

question from:https://stackoverflow.com/questions/65839393/pandasis-there-anyway-to-calculate-cumulative-travel-distance-faster-or-simple

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try the vectorized Pandas functions:

((x_pd.diff()**2 + y_pd.diff()**2)**.5).sum()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...