pandas.DatetimeIndex.snap时间戳到左出现的频率 [英] pandas.DatetimeIndex.snap timestamps to left occurring frequency

查看:121
本文介绍了pandas.DatetimeIndex.snap时间戳到左出现的频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望具有与快照相同的功能,但要使用向左出现的频率,而不是最接近的频率.

I would like to have the same functionality that snap but using the left occurring frequency instead of the nearest.

这是我正在尝试的:

date = pd.date_range('2015-01-01', '2015-12-31')
week_index = pd.DatetimeIndex.snap(date, 'W-MON')
week_index
DatetimeIndex(['2014-12-29', '2015-01-05', '2015-01-05', '2015-01-05',
               '2015-01-05', '2015-01-05', '2015-01-05', '2015-01-05',
               '2015-01-12', '2015-01-12',
               ...
               '2015-12-21', '2015-12-21', '2015-12-21', '2015-12-28',
               '2015-12-28', '2015-12-28', '2015-12-28', '2015-12-28',
               '2015-12-28', '2015-12-28'],
              dtype='datetime64[ns]', length=365, freq='W-MON')

尽管地板会输出ValueError,但似乎应该执行该操作:

It seems like floor should do it, although it outputs ValueError:

week_index = pd.DatetimeIndex.floor(date, 'W-MON')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-40-a053b5230ee3> in <module>()
----> 1 week_index = pd.DatetimeIndex.floor(date, 'W-MON')

C:\ProgramData\Anaconda3\lib\site-packages\pandas\tseries\base.py in floor(self, freq)
     99     @Appender(_round_doc % "floor")
    100     def floor(self, freq):
--> 101         return self._round(freq, np.floor)
    102 
    103     @Appender(_round_doc % "ceil")

C:\ProgramData\Anaconda3\lib\site-packages\pandas\tseries\base.py in _round(self, freq, rounder)
     79 
     80         from pandas.tseries.frequencies import to_offset
---> 81         unit = to_offset(freq).nanos
     82 
     83         # round the local times

C:\ProgramData\Anaconda3\lib\site-packages\pandas\tseries\offsets.py in nanos(self)
    510     @property
    511     def nanos(self):
--> 512         raise ValueError("{0} is a non-fixed frequency".format(self))
    513 
    514 

ValueError: <Week: weekday=0> is a non-fixed frequency

推荐答案

我在pandas snap源代码中找到了解决方案:

I find the solution in pandas snap source code:

改用回滚:

from pandas.tseries.frequencies import to_offset  
freq = to_offset('W-MON')  
date.map(freq.rollback)  

这篇关于pandas.DatetimeIndex.snap时间戳到左出现的频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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