我想在2个月的时间内过滤数据框。我有一个4个月的数据框。
示例数据框:
Index val Datetime
2017-11-01 14:30:00 536.04 2017-11-01 14:30:00
2017-11-01 15:00:00 533.04 2017-11-01 15:00:00
... ... ...
2017-12-31 10:00:00 145.02 2017-12-31 10:00:00
2017-12-31 10:30:00 145.92 2017-12-31 10:30:00
我试过了:
df2[df2['Datetime'] < df2['Datetime'].min() + dateutil.relativedelta.relativedelta(months = 2) + Timedelta('%sD' %x)]
输出:
2017-11-01 14:30:00 536.04 2017-11-01 14:30:00
2017-11-01 15:00:00 533.04 2017-11-01 15:00:00
... ... ...
2017-12-31 10:00:00 145.02 2017-12-31 10:00:00
2017-12-31 10:30:00 145.92 2017-12-31 10:30:00
2017-11-01 14:30:00 536.04 2017-11-01 14:30:00
2017-11-01 15:00:00 533.04 2017-11-01 15:00:00
... ... ...
2018-01-01 10:00:00 145.62 2018-01-01 10:00:00
2018-01-01 10:30:00 151.50 2018-01-01 10:30:00
数据名称增加了1天,但开始日是固定的。
我希望每增加一天将数据帧移动2个月。
预期产出:
2017-11-01 14:30:00 536.04 2017-11-01 14:30:00
2017-11-01 15:00:00 533.04 2017-11-01 15:00:00
... ... ...
2017-12-31 10:00:00 145.02 2017-12-31 10:00:00
2017-12-31 10:30:00 145.92 2017-12-31 10:30:00
2017-11-02 14:30:00 536.04 2017-11-02 14:30:00
2017-11-02 15:00:00 533.04 2017-11-02 15:00:00
... ... ...
2018-01-01 10:00:00 145.62 2018-01-01 10:00:00
2018-01-01 10:30:00 151.50 2018-01-01 10:30:00
答案 0 :(得分:0)
如果我理解正确的话,它应该使用带范围的过滤器。(根据需要用变量替换日期&#39; 12&#39;)
import dateutil
from datetime import datetime,date,timedelta
df2[(df2['Datetime'] > df2['Datetime'].min() + timedelta(days=12)) & (df2['Datetime'] < df2['Datetime'].min() + timedelta(days=2) + dateutil.relativedelta.relativedelta(months=2))]