是否可以将pandas.resample
与给定(任意)DatetimeIndex一起使用(在给定时间窗口使用例如nearest
选项),而不是常规日期的rule
字符串?
编辑:
示例:
dates = pd.DatetimeIndex(['2000-01-01 12:00:00', '2000-01-03 13:00:00', '2000-01-05 15:00:00', '2000-01-09 10:00:00'])
df = pd.DataFrame({'dummy': dates}, index=dates)
custom_dates = pd.DatetimeIndex(['2000-01-02 09:00:00', '2000-01-05 22:00:00', '2000-01-10 15:00:00'])
new_df = df.resample(custom_dates, method='nearest')
new_df
现在应该具有DatetimeIndex custom_dates
和来自df
的列。
答案 0 :(得分:1)
可能有点迟了,但这是一个使用reindex
支持您所需的nearest
选项的解决方案:
import pandas as pd
dates = pd.DatetimeIndex(['2000-01-01 12:00:00', '2000-01-03 13:00:00', '2000-01-05 15:00:00', '2000-01-09 10:00:00'])
df = pd.DataFrame({'dummy': dates}, index=dates)
custom_dates = pd.DatetimeIndex(['2000-01-02 09:00:00', '2000-01-05 22:00:00', '2000-01-10 15:00:00'])
df.reindex(custom_dates, method='nearest', tolerance=pd.Timedelta(2, 'D'))
输出:
dummy
2000-01-02 09:00:00 2000-01-01 12:00:00
2000-01-05 22:00:00 2000-01-05 15:00:00
2000-01-10 15:00:00 2000-01-09 10:00:00