6

I'm trying to calculate the time difference between two rows using shift(), but I get an unexpected error. I may be missing something obvious

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

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

Mark Reed
  • 91,912
  • 16
  • 138
  • 175
Paal
  • 63
  • 1
  • 3

2 Answers2

5

Two things:

If you just want the difference between two consecutive values in the index, you can use the diff method (of a Series, a bit easier than shift and substract):

df['index_col'] = df.index
df['Delta'] = df['index_col'].diff()
joris
  • 133,120
  • 36
  • 247
  • 202
4

Perhaps confusingly, pre-1.0 Series.shift and Index.shift used to not exactly do the same thing, the latter only being meaningfully defined for TimesSeries. Probably easiest to add your index as a column.

df['index_col'] = df.index
df['Delta']=(df['index_col'] - df['index_col'].shift(1))
smci
  • 32,567
  • 20
  • 113
  • 146
chrisb
  • 49,833
  • 8
  • 70
  • 70