UPDATED
I have a df which looks like the following:
print(df)
id rank a
date
2000-01-01 1 1.0 0
2000-01-01 2 3.0 0
2000-01-01 3 2.0 0
2000-01-01 4 0.0 0
2000-01-02 1 2.0 0
2000-01-02 2 3.0 0
2000-01-02 3 2.0 0
2000-01-02 4 1.0 0
2000-01-03 1 3.0 0
2000-01-03 2 2.0 0
2000-01-03 3 1.0 0
2000-01-03 4 1.0 0
I am wanting to create a new variable a
which is equal to 1 if rank
changes from the previous month. For example, in 2000-01-01
rank
is 3.0 and in 2000-01-02
it changes to 2.0. I would like this change to correspond with a 1 in a
and if no change, stay 0. I want to groupby id
aswell. Also, rank can only increase by 1 over each period.
Expected Output
id rank a
date
2000-01-01 1 1.0 1
2000-01-01 2 3.0 1
2000-01-01 3 2.0 1
2000-01-01 4 0.0 1
2000-01-02 1 2.0 1
2000-01-02 2 3.0 0
2000-01-02 3 2.0 0
2000-01-02 4 1.0 1
2000-01-03 1 3.0 1
2000-01-03 2 2.0 1
2000-01-03 3 1.0 1
2000-01-03 4 1.0 0
Any help would be awesome!