Python 熊猫过滤日期,使其持续最近3个月

Python 熊猫过滤日期,使其持续最近3个月,python,pandas,datetime,filter,Python,Pandas,Datetime,Filter,我想筛选最近3个月的熊猫数据帧 import pandas as pd dates = pd.DataFrame(['2016-11-01', '2016-12-01', '2017-01-01', '2017-02-01', '2017-03-01'], columns=['date']) dates.date = pd.DatetimeIndex(dates.date) import datetime today = datetime.date.today() first = today.r

我想筛选最近3个月的熊猫数据帧

import pandas as pd
dates = pd.DataFrame(['2016-11-01', '2016-12-01', '2017-01-01', '2017-02-01', '2017-03-01'], columns=['date'])
dates.date = pd.DatetimeIndex(dates.date)
import datetime
today = datetime.date.today()
first = today.replace(day=1)
lastMonth = first - datetime.timedelta(days=90)
print (lastMonth.strftime("%Y-%m"))
dates[dates.date >= lastMonth]
这段代码已经可以使用了,但是将一个月的长度硬编码为30天。我如何使用
pd.Timedelta('-3个月')
(它似乎不是这样工作的)来实现更强大的功能?

我认为您需要,因为
Timedelta
只对月份不起作用:

lastMonth = first - pd.offsets.MonthBegin(3)
#lastMonth = first - pd.offsets.relativedelta(months=3)

ValueError:无法从传递的参数构造Timedelta,允许的关键字为 [周、日、时、分、秒、毫秒、微秒、纳秒]

lastMonth = first - pd.Timedelta(months=3)