I have a data-frame, df
ID year Treat
1 2008 0
1 2009 2009
1 2010 2010
1 2011 0
2 2008 0
2 2009 0
2 2010 0
2 2011 0
I wanna generate a new variable new_treat:
ID year Treat new_treat
1 2008 0 2009
1 2009 2009 2009
1 2010 2010 2009
1 2011 0 2009
2 2008 0 0
2 2009 0 0
2 2010 0 0
2 2011 0 0
I used the following code:
df['new_treat']= df.groupby(['id'])['treat'].shift(-1)
and
df['new_treat'] = df.groupby('id')['new_treat'].cummin()
It works with first two row but for the remaining I am getting zero.
Treatcummin()method works correctly. 0 is less than 2009. You may want to set the 0 values to NaN first..cummin()will do what you want.