title: How to sessionize data in python
body: <p>I have a requirement to tag user transactions to a session.</p>
  <p>A session is defined in such a way that all actions of a user that happens within 5 minutes after the first action of a session belong to that session. We identify a user by the userID</p>
  <p><strong>Sample Source Data</strong></p>
  <pre class="lang-none prettyprint-override"><code>userID  timestamp
  1.0     2018-04-08 09:47:57.849
  1.0     2018-04-08 09:48:38.762
  1.0     2018-04-08 09:49:31.455
  1.0     2018-04-08 09:53:18.131
  1.0     2018-04-08 09:55:42.875
  1.0     2018-04-08 10:15:04.757
  2.0     2018-04-08 10:15:41.368
  2.0     2018-04-08 10:19:10.744
  2.0     2018-04-08 19:20:37.441
  3.0     2018-04-08 19:21:00.315
  </code></pre>
  <p><strong>Expected Output</strong></p>
  <pre class="lang-none prettyprint-override"><code>userID  timestamp                NewSession
  1.0     2018-04-08 09:47:57.849  1
  1.0     2018-04-08 09:48:38.762  0
  1.0     2018-04-08 09:49:31.455  0
  1.0     2018-04-08 09:53:18.131  1
  1.0     2018-04-08 09:55:42.875  0
  1.0     2018-04-08 10:15:04.757  1
  2.0     2018-04-08 10:15:41.368  1
  2.0     2018-04-08 10:19:10.744  0
  2.0     2018-04-08 19:20:55.441  1
  3.0     2018-04-08 19:21:00.315  1
  </code></pre>
  <p>I am new to python, so need community help.
  I wrote below python code but it is checking 5 min gap between two consecutive transaction whereas I need to map all transaction to same session which is within 5 min internal.</p>
  <pre class="lang-none prettyprint-override"><code>df = pd.read_csv(r&quot;.\Data\Test.csv&quot;, names=['userID','timestamp'], 
                   parse_dates=[1])
  
  df.sort_values(by=['userID','timestamp'], inplace=True)
  
  cond1 = df.timestamp-df.timestamp.shift(1) &gt; pd.Timedelta(5, 'm')
  cond2 = df.userID != df.userID.shift(1)
  df['SessionID'] = (cond1|cond2).cumsum()
  </code></pre>