Select from dataframe the last n records before event appears
<p>Suppose I have the following pandas Dataframe:</p>

<pre><code>      name           timestamp        
1    event1      9/2016 13:47:49          
1    event2      9/2016 13:47:55          
1    event3      9/2016 13:49:30          
1    event4      9/2016 13:50:49          
1    trigger     9/2016 13:51:49          
1    event6      9/2016 13:54:49          
1    event7      9/2016 13:55:49          
1    event8      9/2016 13:56:49          
1    event9      9/2016 13:57:49          
1    trigger     9/2016 13:58:49          
1    event10     9/2016 13:59:49          
1    event11     9/2016 13:59:59         
1    event12     9/2016 14:00:49          
1    event13     9/2016 14:00:59          
1    event14     9/2016 14:01:49     
</code></pre>

<p>What I am trying to do is the following:
Whenever there is a trigger column appearing, I would like to select the last 3 records. So at the end I want to have this:</p>

<pre><code>      name           timestamp   
1    event2      9/2016 13:47:55          
1    event3      9/2016 13:49:30          
1    event4      9/2016 13:50:49 
1    event7      9/2016 13:55:49          
1    event8      9/2016 13:56:49          
1    event9      9/2016 13:57:49 
</code></pre>

<p>Is there a nice predefined pandas function to do that or will I have to iterate the dataframe and get them manually? </p>

<p>thank you!</p>

<p>You can create a group variable based on the <code>cumsum</code> of whether <code>name</code> column is equal to <code>trigger</code> condition and then take the last three records for each group (the last group needs to be filtered out due to the fact that there is no <code>trigger</code> after it):</p>

<pre><code>g = (df.name == 'trigger').cumsum()

df[g &lt; g.max()].groupby(g[g &lt; g.max()]).tail(3)

#     name        timestamp
#1  event2  9/2016 13:47:55
#1  event3  9/2016 13:49:30
#1  event4  9/2016 13:50:49
#1  event7  9/2016 13:55:49
#1  event8  9/2016 13:56:49
#1  event9  9/2016 13:57:49
</code></pre>

python pandas select dataframe