问题
I would like to have the same functionality that snap but using the left occurring frequency instead of the nearest.
This is what I am trying:
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')
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
回答1:
I find the solution in pandas snap source code:
use rollback instead:
from pandas.tseries.frequencies import to_offset
freq = to_offset('W-MON')
date.map(freq.rollback)
来源:https://stackoverflow.com/questions/45962669/pandas-datetimeindex-snap-timestamps-to-left-occurring-frequency