nilesh
nilesh

Reputation: 347

pandas get index of previous date

I have pandas dataframe with date a column, I want to add a new column with previous date index in the dataframe. How to achieve this? Sample df:

index Date
0 2015-10-03 
1 2015-11-03 
2 2015-11-30 
3 2015-11-30  
4 2015-12-03 

Desired output:

index Date previous_day
0 2015-10-03 0
1 2015-11-03 0
2 2015-11-30 1
3 2015-11-30 1 
4 2015-12-03 3
  1. Since at index 1 there is no previous day i want 1 in previous day.
  2. Since date at index 2 is same as index 3 I expect 1 in previous_day for index 3.

Thanks,

Upvotes: 1

Views: 666

Answers (1)

jezrael
jezrael

Reputation: 862406

I think you need replace index of duplicated values of Date column to NaN and then forwarding filling these values. Also is necessary rename first value of index to 1 and last subtract 1:

Notice: Solution works only if unique monotonic index (0,1,2,...)

#see notice above 
df.reset_index(drop = True, inplace = True)

df['prev'] = df.rename(index={0:1})
              .index.to_series()
              .where(~df['Date'].duplicated()).ffill()
              .astype(int)
              .sub(1).values
print (df)
            Date  prev
index                 
0     2015-10-03     0
1     2015-11-03     0
2     2015-11-30     1
3     2015-11-30     1
4     2015-12-03     3

Upvotes: 1

Related Questions