Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get previous week value Python dataframe

I have the following dataframe:

Date        Time    Quantity  
20171003    5:00           2       
20171003    5:15           5  
....
20171005    5:00           1   
20171005    5:15           9  

I need to create a new column containing the quantity of the same day of the previous week, that is:

Date        Time    Quantity    Quantity-1
20171003    5:00           2         NaN
20171003    5:15           5         NaN
....
20171005    5:00           1           2
20171005    5:15           9           5

I figured out how to get the same day of the last week by using for example:

last_week = today() + relativedelta(weeks=-1, weekday= now.weekday())

How to apply this to my dataframe?

Thank you in advance!

like image 847
Batmax Avatar asked Feb 07 '26 00:02

Batmax


1 Answers

Does your index have a pattern? If yes, you could use pd.shift(). The periods paramater would be the number of periods in your df. For example, assuming your Time column is always whether 5:00 or 5:15, and that you have calendar days, your period would be 7 * 2 = 14

df['Quantity-1'] = df['Quantity'].shift(14)
like image 173
Eric B Avatar answered Feb 08 '26 14:02

Eric B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!