0

I am trying to convert a series of Dates to a series of Date Intervals but cannot figure out how to do it in one beautiful query. I would like it to operate in the same way that the .diff() method operates. See the image of the behavior I am expecting.

image

I have nearly extracted the information I am looking for with this like code:

dates = {}
for key,item in app.sort_values('Date').groupby('UniqueId'):
    x = list(item.Date)
    date_range = []
    for k in range(0,len(x)-1):
        date_range.append([x[k],x[k+1]])
        
    dates.update({key:date_range})

Any Direction Helps. Thanks!

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • `df['Intervals'] = list(zip(df['Dates'].shift(-1), df['Dates']))` (convert two columns to a tuple https://stackoverflow.com/a/16068497/5125264 plus the lag operator to shift the series by one https://stackoverflow.com/a/66258734/5125264) – Matt May 26 '21 at 18:22
  • Fantastic this works as intended. Thank you!!! – Riley Michael May 26 '21 at 19:17

1 Answers1

0

Try using pandas shift

# Create dataframe
dates=['12/14/20 18:28','12/16/20 18:28','12/19/20 18:36','5/18/21 23:48']
cols=['dates']
df=pd.DataFrame(dates, columns=cols)

df['intervals'] = df['dates'].shift(1)+','+df['dates']
David Molina
  • 141
  • 1
  • 7