I have a dataframe df
:
df = pd.DataFrame({'id1':[1,1,1,1,1,4,4,4,6,6],
'id2':[45,45,33,33,33,1,1,1,34,34],
'vals':[0.1,0.2,0.6,0.1,0.15,0.34,0.12,0.5,0.4,0.45],
'date':pd.to_datetime(['2017-01-01','2017-01-02','2017-01-01',
'2017-04-01','2017-04-02','2017-01-01',
'2017-01-02','2017-01-03','2017-01-04',
'2017-01-05'])})
I want to create lag terms based on time for each group of id1
and id2
. For example, t_1
would be the value from the day before. t_2
would be the value from two days before. If there is no value from two-days before, I would like it to be nan
. This would be the output for the above dataframe:
date id1 id2 vals t_1 t_2
0 2017-01-01 1 33 0.60 NaN NaN
1 2017-04-01 1 33 0.10 NaN NaN
2 2017-04-02 1 33 0.15 0.10 NaN
0 2017-01-01 1 45 0.10 NaN NaN
1 2017-01-02 1 45 0.20 0.10 NaN
0 2017-01-01 4 1 0.34 NaN NaN
1 2017-01-02 4 1 0.12 0.34 NaN
2 2017-01-03 4 1 0.50 0.12 0.34
0 2017-01-04 6 34 0.40 NaN NaN
1 2017-01-05 6 34 0.45 0.40 NaN
I can do this by using the code below, but it is extremely inefficient for a large number of groups - i.e. if I have 10000 x 500 unique combinations of id1
and id2
, several days of data for each, and I want 2 lag terms, it takes a long time.
num_of_lags = 2
for i in range(1, num_of_lags+1):
final = pd.DataFrame()
for name, group in df.groupby(['id1', 'id2']):
temp = group.set_index('date', verify_integrity=False)
temp = temp.shift(i, 'D').rename(columns={'vals':'t_' + str(i)}).reset_index()
group = pd.merge(group, temp[['id1', 'id2', 'date', 't_' + str(i)]],
on=['id1', 'id2', 'date'], how='left')
final = pd.concat([final, group], axis=0)
df = final.copy()
Is there a more efficient way of doing this?
id1
andid2
? Looks like you're just usingvals
. – Buyersid1
andid2
is that I am grouping by those - so I only want lag variables within each unique combo ofid1
andid2
. Therefore I can't just do.shift(1, freq='D')
on the entire dataframe – Chelsiechelsy