title: Quick way to find previous instance of a value in a pandas Dataframe or numpy array?
body: <p>I have an large data set (number of rows in millions) which I read into a pandas DataFrame called <strong>datafile</strong>. </p>
  
  <p>Each row has an Order ID number - this is non-unique. So my <strong>datafile</strong> looks something like this</p>
  
  <pre><code>Price   Qty           OrderId
  
  26690  3000  1213772
  
  26700  3000  1215673
  
  26705  6000  1216656
  
  26700  3000  1213772
  
  26710  3000  1215673
  </code></pre>
  
  <p>Now, what I want is, for each row - get the OrderID, find the previous occurrence of that OrderID in the DataFrame and get the corresponding price, and populate it in a new column "Prev_Price". If no previous occurrence is found, keep the value as 0. So my output should look like this</p>
  
  <pre><code>Price   Qty           OrderId  Prev_Price
  
  26690  3000  1213772 0
  
  26700  3000  1215673 0
  
  26705  6000  1216656 0
  
  26700  3000  1213772 26690
  
  26710  3000  1215673 26700
  </code></pre>
  
  <p>I tried using numpy and wrote this function </p>
  
  <pre class="lang-py prettyprint-override"><code>def getPrevPrice_np(x):
      try:
          return list(datanp[np.where(datanp[0:x,2]==datanp[x,2])][:,0])[-1]
      except:
          return 0
  </code></pre>
  
  <p>which I'm applying like this </p>
  
  <pre class="lang-py prettyprint-override"><code>datanp = datafile.values
  datafile['Prev_Price'] = pd.Series(datafile.index).apply(getPrevPrice_np)
  </code></pre>
  
  <p>But it is still quite slow for my requirement - what would be the fastest way to implement this?</p>