title: Pandas - groupby if Criteria Met
body: <p>The data below is based on GPS coordinates of a van, whether the ignition was on/off, and how far the van was from a target location at a given time. I want to determine whether a van was at or near a location (&lt;300), whether the ignition was turned off, and if both conditions are true, the time duration of the stay. </p>
  
  <p>In the example below, I visualize rows 1-4 as being "grouped" together since they are consecutive rows where the distance was &lt;300. Row 5 is "grouped" on its own since it was >300, and rows 6-8 are "grouped" together since they are consecutive rows with distance &lt;300.</p>
  
  <p>Accordingly, since the ignition was turned off in rows 1-4, I want to calculate the time duration (since the van "stopped" at the location for a given amount of time). However, the other two groups (row 5 and rows 6-8) should not have a time duration calculation since the ignition was never turned off in those groupings.</p>
  
  <pre><code>df
  AcctID   On_Off    Distance  Timestamp
  123      On        230       12:00
  123      On        30        12:02
  123      Off       29        12:05
  123      Off       35        12:10
  123      On        3000      12:13
  123      On        100       12:20
  123      On        95        12:22
  123      On        240       12:28
  </code></pre>
  
  <p>I'm able to classify whether the Distance is less than 300 (<code>Within_Distance</code>), but determining whether the ignition was off for at least one of the rows in the grouping has me stumped. Here's what the final dataframe should look like:</p>
  
  <pre><code>df['Within_Distance'] = np.where(df['Distance']&lt;300, "Yes", "No")
  
  df
  AcctID   On_Off    Distance  Timestamp   Within_Distance    Was_Off    Within_Distance_and_Was_Off
  123      On        230       12:20       Yes                Yes        Yes
  123      On        30        12:02       Yes                Yes        Yes
  123      Off       29        12:05       Yes                Yes        Yes
  123      Off       35        12:10       Yes                Yes        Yes
  123      On        3000      12:13       No                 No         No
  123      On        100       12:20       Yes                No         No
  123      On        95        12:22       Yes                No         No
  123      On        240       12:28       Yes                No         No
  </code></pre>
  
  <p>Thanks in advance!</p>