Windstorm1981
Windstorm1981

Reputation: 2680

Rolling A DatetimeIndex Forward to the Beginning of the Next Business Month in Pandas

I'm using Python 2.7 and Pandas 0.19.2

I have a dataframe as follows:

                Frequency       Percentage
Date             0.033464       0.138084  
2016-10-27       0.174455       0.114329          
2016-11-28       0.116002       0.106543         
2016-12-23       0.113620       0.105842          
2017-01-31       0.115948       0.119684      

I want to move the DatetimeIndex forward to the first business day of the following month:

                Frequency       Percentage
Date             0.033464       0.138084  
2016-11-01       0.174455       0.114329          
2016-12-01       0.116002       0.106543         
2017-01-02       0.113620       0.105842          
2017-02-01       0.115948       0.119684   

I cant just add a fixed number of days because the date of each value varies relative to month end. Also, the first day of the month may be a weekend and I want the first business day.

I experimented a bit with pandas.timeseries.offsets trying to use BMonthBegin() but couldn't get it to work because this module seems to like timestamps and not DatetimeIndexes.

Can anyone help?

Thanks in advance. I'm not yet that strong with datetime objects.

Upvotes: 2

Views: 1365

Answers (1)

miradulo
miradulo

Reputation: 29690

You could add to the index with pd.offsets.BMonthBegin() as you were attempting to do. Notice that this offset doesn't have a vectorized implementation, and so as far as I know may be significantly slower than some other offsets like Day, and thus raise a PerformanceWarning.

Demo

>>> df.index += pd.offsets.BMonthBegin(1)
PerformanceWarning: Non-vectorized DateOffset being applied to Series or DatetimeIndex
  "or DatetimeIndex", PerformanceWarning)

>>> df

            Frequency  Percentage
2016-11-01   0.174455    0.114329
2016-12-01   0.116002    0.106543
2017-01-02   0.113620    0.105842
2017-02-01   0.115948    0.119684

Upvotes: 2

Related Questions