在 pandas 中将DatetimeIndex滚动到下一个工作月的开始 [英] Rolling A DatetimeIndex Forward to the Beginning of the Next Business Month in Pandas

查看:104
本文介绍了在 pandas 中将DatetimeIndex滚动到下一个工作月的开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python 2.7和Pandas 0.19.2

I'm using Python 2.7 and Pandas 0.19.2

我有如下数据框:

                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      

我想将DatetimeIndex移至下个月的第一个工作日:

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.

我尝试了pandas.timeseries.offsets尝试使用BMonthBegin( ),但由于该模块似乎喜欢时间戳而不是DatetimeIndexes而无法正常工作。

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.

有人可以帮忙吗?

预先感谢。我对日期时间对象还不够强。

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

推荐答案

您可以使用 pd.offsets.BMonthBegin() ,因为您尝试这样做。请注意,此偏移量没有向量化的实现,据我所知,它可能比 Day 之类的其他偏移量要慢得多,因此提高了 PerformanceWarning

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.

演示

>>> 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

这篇关于在 pandas 中将DatetimeIndex滚动到下一个工作月的开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆