I have an large data set (number of rows in millions) which I read into a pandas DataFrame called datafile.
Each row has an Order ID number - this is non-unique. So my datafile looks something like this
Price Qty OrderId
26690 3000 1213772
26700 3000 1215673
26705 6000 1216656
26700 3000 1213772
26710 3000 1215673
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
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
I tried using numpy and wrote this function
def getPrevPrice_np(x):
try:
return list(datanp[np.where(datanp[0:x,2]==datanp[x,2])][:,0])[-1]
except:
return 0
which I'm applying like this
datanp = datafile.values
datafile['Prev_Price'] = pd.Series(datafile.index).apply(getPrevPrice_np)
But it is still quite slow for my requirement - what would be the fastest way to implement this?