1 回答
TA贡献1828条经验 获得超4个赞
x = pd.date_range('01-01-2019', freq='1D', periods=7)
y = pd.date_range('01-01-2022', freq='1D', periods=7)
def floor(x, freq):
offset = x[0].ceil(freq) - x[0]
return (x + offset).floor(freq) - offset
print(floor(x, '3D'))
print(floor(y, '3D'))
输出
DatetimeIndex(['2019-01-01', '2019-01-01', '2019-01-01', '2019-01-04',
'2019-01-04', '2019-01-04', '2019-01-07'],
dtype='datetime64[ns]', freq=None)
DatetimeIndex(['2022-01-01', '2022-01-01', '2022-01-01', '2022-01-04',
'2022-01-04', '2022-01-04', '2022-01-07'],
dtype='datetime64[ns]', freq=None)
添加加法逻辑:
def floor(x, freq):
offset = x[0].ceil(freq) - x[0]
adj_needed = (offset != pd.Timedelta(0))
return (x + offset).floor(freq) - offset if adj_needed else x.floor(freq)
添加回答
举报