-2

I have a pandas data frame with a column representing dates in the format yyyy-mm-dd. This are sorted oldest to newest. I want to add a column next to it with the difference in time between the date at that row and the previous date.

In excel this would be something like:

enter image description here

1
  • Where exactly are you struggling with this?
    – That1Guy
    Nov 6, 2015 at 17:20

2 Answers 2

2

Assuming your "date" column is stored as a datetime64 type, you can just do

df['difference'] = df.date.diff()

Check df.dtypes to ensure the date type is correct first.

-1

solved it

data['lowered'] = data['date'].shift(+1)

data['difference'] =  data['date'] - data['lowered']
1
  • 1
    That's a lot slower than calling diff() because you are unnecessarily creating temporary variables. Nov 6, 2015 at 17:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.