I am trying to compute the difference in timestamps and make a delta time column in a Pandas dataframe. This is the code I am currently using:
# Make x sequential in time
x.sort_values('timeseries',ascending=False)
x.reset_index(drop=True)
# Initialize a list to store the delta values
time_delta = [pd._libs.tslib.Timedelta('NaT')]
# Loop though the table and compute deltas
for i in range(1,len(x)):
time_delta.append(x.loc[i,'timestamp'] - x.loc[i-1,'timestamp'])
# Compute a Pandas Series from the list
time_delta = pd.Series(time_delta)
# Attach the Series back to the original df
x['time_delta'] = time_delta
It seems like there should be a more efficient / vectorized way of doing this simple operation, but I can't seem to figure it out.
Suggestions on improving this code would be greatly appreciated.