我希望具有相同的功能,但使用左出现的频率而不是最近的频率。
这就是我的尝试:
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:
,但它似乎应该这样做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
答案 0 :(得分:5)
我在pandas snap源代码中找到了解决方案:
改为使用回滚:
from pandas.tseries.frequencies import to_offset
freq = to_offset('W-MON')
date.map(freq.rollback)