title: Pandas groupby: How do I use shifted values
body: <p>I have a dataset that represents reoccurring events at different locations. </p>
  
  <pre><code>df = [Datetime location time event]
  </code></pre>
  
  <p>Each location can have 8-10 events that repeat. What I'm trying to do is build some information of how long it has been between two events. (they may not be the same event)</p>
  
  <p>I am able to do this by splitting the df into sub-dfs and processing each location individually. But it would seem that groupby should be smarter that this. This is also assuming that I know all the locations which may vary file to file.</p>
  
  <pre><code>   df1 = df[(df['location'] == "Loc A")]  
     df1['delta'] = df1['time'] - df1['time'].shift(1)  
  
     df2 = df[(df['location'] == "Loc B")]  
     df2['delta'] = df2['time'] - df2['time'].shift(1)  
     ...
  
  ... 
  </code></pre>
  
  <p>What I would like to do is groupBy based on location...</p>
  
  <pre><code>dfg = df.groupby(['location'])
  </code></pre>
  
  <p>Then for each grouped location<br>
     Add a delta column<br>
     Shift and subtract to get the delta time between events</p>
  
  <p>Questions:<br>
  Does groupby maintain the order of events?<br>
  Would a for loop that runs over the DF be better? That doesn't seem very python like.
  Also once you have a grouped df is there a way to transform it back to a general dataframe. I don't think I need to do this but thought it may be helpful in the future. </p>
  
  <p>Thank you for any support you can offer. </p>