Calculation of the time difference between two rows

I am trying to calculate the time difference between two lines using shift() , but I am getting an unexpected error. Perhaps I will miss something obvious.

 df['Delta'] = (df.index - df.index.shift(1)) 

This statement creates a ValueError: Cannot shift with no offset . What am I missing?

+5
source share
2 answers

Two things:

If you just want the difference between two consecutive values โ€‹โ€‹in the index, you can use the diff method (from a series, a little easier than shift and subtraction):

 df['index_col'] = df.index df['Delta'] = df['index_col'].diff() 
+4
source

Perhaps vaguely, Series.shift and Index.shift do not exactly do the same, the latter only for a meaningful definition for the TimesSeries. Probably the easiest way is to add your index as a column.

 df['index_col'] = df.index df['Delta']=(df['index_col'] - df['index_col'].shift(1)) 
+2
source

Source: https://habr.com/ru/post/1200418/


All Articles