title: Getting the start and end dates of a patient, with the possibility of multiple "episodes"
body: <p>I'm trying to create a sub-data from a dataset where it has the start date, end date and the episode number of all individuals that ever was in the ICU.</p>
  <p><strong>Desired outcome</strong></p>
  <p>The outcome i would like to have look as follows, where episode 1 is the first period the individual was in ICU, episode 2 is the second time they were in ICU so on and so forth.</p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>Patient</th>
  <th>Start Date</th>
  <th>End Date</th>
  <th>Episode</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>Individual A</td>
  <td>3/5/2021</td>
  <td>5/5/2021</td>
  <td>1</td>
  </tr>
  <tr>
  <td>Individual A</td>
  <td>10/5/2021</td>
  <td>11/5/2021</td>
  <td>2</td>
  </tr>
  <tr>
  <td>Individual B</td>
  <td>6/6/2021</td>
  <td>16/6/2021</td>
  <td>1</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p><strong>DATASET</strong></p>
  <p>The dataset I have is in a long format, and we are only interested in whether the status of a patient is &quot;in ICU&quot;.</p>
  <p>Example of a few columns (mainly for individual A)</p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>Patient</th>
  <th>Status</th>
  <th>as of Date</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>Individual A</td>
  <td>In ICU</td>
  <td>3/5/2021</td>
  </tr>
  <tr>
  <td>Individual A</td>
  <td>In ICU</td>
  <td>4/5/2021</td>
  </tr>
  <tr>
  <td>Individual A</td>
  <td>In ICU</td>
  <td>5/5/2021</td>
  </tr>
  <tr>
  <td>Individual A</td>
  <td>Not in ICU</td>
  <td>6/5/2021</td>
  </tr>
  <tr>
  <td>Individual A</td>
  <td>Not in ICU</td>
  <td>7/5/2021</td>
  </tr>
  <tr>
  <td>Individual A</td>
  <td>Not in ICU</td>
  <td>8/5/2021</td>
  </tr>
  <tr>
  <td>Individual A</td>
  <td>Not in ICU</td>
  <td>9/5/2021</td>
  </tr>
  <tr>
  <td>Individual A</td>
  <td>In ICU</td>
  <td>10/5/2021</td>
  </tr>
  <tr>
  <td>Individual A</td>
  <td>In ICU</td>
  <td>11/5/2021</td>
  </tr>
  <tr>
  <td>Individual A</td>
  <td>Not in ICU</td>
  <td>12/5/2021</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>I have tried a groupby min, max and count by patient in Python but it only gives the earliest start and latest end date for any individual patients. Would appreciate if anyone can share insights on a feasible algorithm for this problem please!
  Solution can be in Python/R/Excel. Thanks alot.</p>