How to extract data from previous 2 years based on particular date in Python?

狂风中的少年 提交于 2021-02-05 11:30:28

问题


I have a csv file consisting of last 3 years of timeseries monthly data. Based on today's date, I would like to read only the previous 2 years of data for forecasting the future.

Data file example (has data from 01-01-15 to 31-10-19):  

    Date,Value
    01-01-17,2   
    01-02-17,5   
    01-03-17,8     
    01-04-17,4  
    01-05-17,2  
    01-06-17,9  
    01-07-17,8  
    01-08-17,7  
    01-09-17,5  
    01-10-17,1  
    01-11-17,2  
    01-12-17,3  
    01-01-18,5  
    01-02-18,6  
    01-03-18,8  
    01-04-18,2  
    01-05-18,5   
    01-06-18,6  

Desired result:
If today's date is 01/01/19, I want my training data to be data from 01/01/17 - 31/12/18.

I tried:
df[df['date'] > (pd.to_datetime('2019-01-01', format = '%Y-%m-%d') - relativedelta(years = 2))]

However, I am getting data from 01-01-17 to 31-10-19(last record) instead of from 01-01-17 to 31-12-18.


回答1:


You can try the following

>>> from dateutil.relativedelta import relativedelta
>>> df[df.Date > datetime.now() - relativedelta(years=2)]
         Date  Value
12 2018-01-01      5
13 2018-01-02      6
14 2018-01-03      8
15 2018-01-04      2
16 2018-01-05      5
17 2018-01-06      6

Update

>>> from dateutil.relativedelta import relativedelta
>>> from datetime import date

>>> start_date = pd.Timestamp(datetime.now() - relativedelta(years=2))
>>> end_date = pd.Timestamp(date(date.today().year-1, 12, 31))

>>> df[(df.Date >= start_date) & (df.Date <= end_date)]

         Date  Value
12 2018-01-01      5
13 2018-01-02      6
14 2018-01-03      8
15 2018-01-04      2
16 2018-01-05      5
17 2018-01-06      6


来源:https://stackoverflow.com/questions/59491093/how-to-extract-data-from-previous-2-years-based-on-particular-date-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!