luca
luca

Reputation: 7546

DatetimeIndex: what is the purpose of 'freq' attribute?

I miss the point of the 'freq' attribute in a pandas DatatimeIndex object. It can be passed at construction time or set at any time as a property but I don't see any difference in the behaviour of the DatatimeIndex object when this property changes.

Plase look at this example. We add 1 day to a DatetimeIndex that has freq='B' but the returned index contains non-business days:

import pandas as pd
from pandas.tseries.offsets import *

rng = pd.date_range('2012-01-05', '2012-01-10', freq=BDay())
index = pd.DatetimeIndex(rng)
print(index)

index2 = index + pd.Timedelta('1D')
print(index2)

This is the output:

DatetimeIndex(['2012-01-05', '2012-01-06', '2012-01-09', '2012-01-10'], dtype='datetime64[ns]', freq='B')

DatetimeIndex(['2012-01-06', '2012-01-07', '2012-01-10', '2012-01-11'], dtype='datetime64[ns]', freq='B')

Upvotes: 1

Views: 231

Answers (2)

luca
luca

Reputation: 7546

From github issue:

The freq attribute is meant to be purely descriptive, so it doesn't and shouldn't impact calculations. Potentially docs could be clearer.

Upvotes: 0

BENY
BENY

Reputation: 323366

You are looking for shift

index.shift(1)
Out[336]: DatetimeIndex(['2012-01-06', '2012-01-09', '2012-01-10', '2012-01-11'], dtype='datetime64[ns]', freq='B')

Also BDay will do that too

from pandas.tseries.offsets import BDay
index + BDay(1)
Out[340]: DatetimeIndex(['2012-01-06', '2012-01-09', '2012-01-10', '2012-01-11'], dtype='datetime64[ns]', freq='B')

Upvotes: 2

Related Questions