This is a sample of my real dataset.
data = {'CarNo': [888, 81, 16, 62, 31, 23, 777, 23, 777, 31, 888, 62, 81, 16, 888, 31, 81, 62, 16, 23],
'LapTime': [119628, 117170, 119846, 117178, 119516, 117915, 116964, 116683, 117169, 118919, 119227, 117789, 117674, 116914, 116333, 120027, 116403, 117351, 116557, 117107],
'LAPS': [147.0, 147.0, 147.0, 147.0, 147.0, 146.0, 121.0, 56.0, 55.0, 55.0, 55.0, 54.0, 54.0, 54.0, 123.0, 123.0, 123.0, 123.0, 123.0, 122.0],
'UpdateTime': [162047732, 162047732, 162047732, 162047732, 162047732, 162047732, 162047732, 125626988, 125626988, 125626988, 125626988, 125626988, 125626988, 125626988, 151851068, 151851068, 151851068, 151851068, 151851068, 151851068],
'rank': [6.0, 2.0, 7.0, 3.0, 5.0, 4.0, 1.0, 1.0, 3.0, 6.0, 7.0, 5.0, 4.0, 2.0, 1.0, 7.0, 2.0, 5.0, 3.0, 4.0]
}
df = pd.DataFrame(data)
df
I want to groupby according to the "UpdateTime" then find the gap between each row and Rank one in each group. From other questions here, I did something like bellow. but it is not very clever and I am also loosing my first row. Please help.
def diff_to_top(df,colA):
pos=sub.columns.get_loc(colA)
gap = sub.iloc[1:, pos] - sub.iat[0, pos]
return gap
sub = df.set_index(['UpdateTime','rank','LAPS'])
sub.sort_index(inplace=True, ascending=True)
diff_to_top(sub,'LapTime')