I have the following challenge: I have a PandasDataframe with information about a unique ArucoID, a unique frameID and associated coordinates in a coordinate system. For example like this:
# import pandas library
import pandas as pd
# lst_of_dfs = []
# dictionary with list object of values
data1 = {
'frameID' : [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
'xPos' : [10.0, 10.5, 11.0, 12.0, 13, 4.0, 5.0, 6.0, 7.0, 9.0, 1.5, 2.0, 2.5, 3.0, 4.0 ],
'yPos' : [-0.2, -0.1, -0.1, 0.0, 0.0, 0.2, 0.2, -0.1, 0.0, 0.05, -0.2, -0.1, 0.0, 0.1, 0.05],
'ArucoID' : [910, 910, 910, 910, 910, 898, 898, 898, 898, 898, 912, 912, 912, 912, 912],
'Subtrial' : ['01', '01', '01', '01', '01', '01', '01', '01', '01', '01', '01', '01', '01', '01', '01']
}
df1 = pd.DataFrame(data1)
data2 = {
'frameID' : [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
'xPos' : [9.4, 9.5, 9.0, 9.0, 10, 3.0, 4.0, 5.0, 6.0, 7.0, 2.5, 3.0, 3.5, 3.5, 5.0 ],
'yPos' : [-0.2, -0.1, -0.1, 0.0, 0.0, 0.2, 0.2, -0.1, 0.0, 0.05, -0.2, -0.1, 0.0, 0.1, 0.05],
'ArucoID' : [910, 910, 910, 910, 910, 898, 898, 898, 898, 898, 912, 912, 912, 912, 912],
'Subtrial' : ['02', '02', '02', '02', '02', '02', '02', '02', '02', '02', '02', '02', '02', '02', '02']
}
df2 = pd.DataFrame(data2)
lst_of_dfs = [df1,df2]
# creating a Dataframe object
df_TrajData = pd.concat(lst_of_dfs)
#print(df_TrajData)
Now I calculate the distance between the xPos as rolling mean for the DataFrame grouped by ArucoID:
#calculation of current distance of each ArucoID as rolling mean over a window of n frames (n is set as 2 frames for testing)
all_data = []
df_grouped = df_TrajData.groupby('ArucoID')
for key, data in df_grouped:
#calc distance covered in window
dX = data['xPos'] - data['xPos'].shift(2)
#print(dX)
data['dX'] = dX
all_data.append(data)
df = pd.concat(all_data)
#print(df)
And now I get into trouble: I want to calculate the speed [s]. That would be v = dX / (time[-1] - time[0] / framerate), where time[-1] is last frameID of the rolling window, t[0] current frameID and framerate is 30 frames/per/second.
I was starting with (rolling_window=3, min_periods=1):
df['speed'] = df.groupby('ArucoID')['dX'].transform(lambda x: x.rolling(3, 1).mean())
which is the calculation of the rolling distance. What I would actually like to do would be something like that:
df['speed'] = df.groupby('ArucoID')['dX'].transform(lambda s: s.rolling(3, min_periods=1).mean() / (t[-1] - t[0] /framerate))
#print(df)
Any suggestions would be appreciated. Many thanks in advance!

