I was wondering if there was some function/library that can calculate velocity in a pandas dataframe. I have the following dataframe:
Time bar_head_x bar_head_y bar_head_z
0.00 -203.3502 1554.3486 1102.8210
0.01 -203.4280 1554.3492 1103.0592
0.02 -203.4954 1554.3234 1103.2794
0.03 -203.5022 1554.2974 1103.4522
From this I want to calculate speed, velocity and acceleration. Speed and acceleration are easy: I used np.linalg.norm
to calculate the speed, like so:
speed['head'] = np.linalg.norm(speed[['bar_head_x','bar_head_y','bar_head_z']].values,axis=1)
and .diff()
to calculate acceleration from speed, like so:
acc['acc_head'] = (speed['head'].diff()) / ((speed['Time'].diff()))
But how would I go about calculating velocity in such a simple way? Is there such a way - a function to help do this?
Thanks!
df.diff() gives you the next minus the current row.
Since your bar_head...
columns indicate position, the differences generated by df.diff can be intepreted as the vectors pointing from current to next positions. np.linalg.norm of these vectors gives you the length of the vectors, i.e. distance travelled per interval. Division by the time interval gives velocity.
diff = df.diff()
coords = [c for c in df.columns if not 'Time' in c]
np.linalg.norm(diff[coords], axis=1)/diff['Time']
0 NaN
1 25.058420
2 23.172492
3 17.487733
explananation for the 2D case
suppose we have the following dataframe:
df = pd.DataFrame({'time':[0,1], 'x':[1,2], 'y':[1,2]})
time x y
0 0 1 1
1 1 2 2
at time=0 we are at position [1,1] at time=1 we have moved to position [2,2]
so, we have traveled 1 in direction x and 1 in direction y. Our total distance travelled is sqrt(1^2 + 1^2) = sqrt(2)
using df.diff(), we get
time x y
0 NaN NaN NaN
1 1.0 1.0 1.0
Here, we interpret the 1.0, 1.0 in row 1 as the vector that points from our position at time t=0 to our position at time t=1.
The length of that vector can be computed by its norm, and likewise evaluates to the square root of 2.
So, we can use np.linalg.norm to calculate the distance travelled per time interval.
The velocity is simply (distance travelled)/(length of time interval)