Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do date_range in reverse?

I'm dealing with problem how to create date range in reverse. I'm trying this:

import pandas as pd
dates = pd.date_range(end='2/08/2014', periods=104, freq='W-Sat', closed = None)

Always i get from later to sooner like following:

<class 'pandas.tseries.index.DatetimeIndex'>
[2012-02-18, ..., 2014-02-08]
Length: 104, Freq: W-SAT, Timezone: None

I want to range starting with '2014-02-08'.

Thanks

Solution:

Thanks for pointing out built-in reverse functionality, you need to go back and create DatetimeIndex to use it in Time Series like this:

dTmp = pd.date_range(end='2/08/2014', periods=104, freq='W-Sat', closed = None)
dates = [d for d in reversed(dTmp)]`
like image 302
Martin Bodocky Avatar asked May 02 '14 00:05

Martin Bodocky


2 Answers

Use could get this directly with fancy indexing:

pandas.date_range(end='2/08/2014', periods=104, freq='W-Sat')[::-1]

like image 133
Paul H Avatar answered Oct 03 '22 07:10

Paul H


You can do this natively by specifying a negative frequency:

import pandas as pd
freq = '-1W-Sat'
dates = pd.date_range(start='2/08/2014', periods=104, freq=freq, closed = None)

note that the start parameter was used.

like image 43
jc416 Avatar answered Oct 03 '22 06:10

jc416