title: Pandas: calculating average behaviour of time series data around an event
body: <p>I have two dataframes with date time information, <code>df_stream</code> is a stream of events and <code>df_events</code> are specific events in time. For example:</p>
  <p><a href="https://i.stack.imgur.com/C4P29.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C4P29.png" alt="Stream (blue) and event (red)" /></a></p>
  <p>The blue is the stream and the red line is the event. The window is <code>30min</code> either side of the event and the time granularity is <code>30s</code>.</p>
  <p><strong>How do I produce a dataframe / graph of the average behaviour of the stream for all events for a given time window and time granularity?</strong></p>
  <p>The stream dataframe looks like:</p>
  <pre><code>                     streamEventId
  DateTime                          
  2020-08-20 10:39:24       44791313
  2020-08-20 10:40:30       44791721
  2020-08-20 10:40:54       44694121
  2020-08-20 10:41:16       44902962
  2020-08-20 10:42:04       44622569
  </code></pre>
  <p>The event dataframe looks like:</p>
  <pre><code>            DateTime
  0 2020-11-17 09:49:00
  1 2020-11-17 10:49:00
  2 2020-11-17 11:11:00
  3 2020-11-17 11:16:00
  4 2020-11-17 12:11:00
  </code></pre>
  <p>I've managed to get graphs of each event with their respective windows printed but am struggling to combine the logic. Also I use <code>iterrows</code> which I am not a fan of.</p>
  <p>My current approach:</p>
  <pre><code>for i in df_events[[&quot;DateTime&quot;]].iterrows():
      date_time = i[1].values[0]
      before = date_time - pd.Timedelta(window)
      after = date_time + pd.Timedelta(window)
  
      df_stream_temp = df_stream.loc[before:after].copy()
      plt.figure(figsize=(20, 2))
      df_stream_mva = (
          df_stream.streamEventId.groupby(pd.Grouper(freq=&quot;30s&quot;))
          .count()
          .loc[before:after]
      )
  
      y_height = df_stream_mva.max()
  
      ax = df_stream_mva.plot()
      plt.vlines(df_events.DateTime.to_list(), 0, y_height, color=&quot;lightcoral&quot;)
      ax.set_ylim([0, y_height]) 
  </code></pre>
  <p>Which gives a nice series of graphs:</p>
  <p><a href="https://i.stack.imgur.com/O6j51.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O6j51.png" alt="Example of graphs of events in stream" /></a></p>
  <p>And so on...</p>
  <p><strong>I would like to calculate and then plot the average of the above with confidence intervals.</strong></p>