熊猫筛选日期持续最近三个月

Geo*_*ler 2 python datetime filter pandas

我想将熊猫数据框过滤到最近的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]
Run Code Online (Sandbox Code Playgroud)

这段代码排序已经工作,但有硬编码为每月30天的长度。我如何使用pd.Timedelta('-3 month')(这似乎并不喜欢这个工作),以实现更强大的功能?

jez*_*ael 5

我认为您需要offsets,因为Timedelta只有几个月才能使用:

lastMonth = first - pd.offsets.MonthBegin(3)
#lastMonth = first - pd.offsets.relativedelta(months=3)
Run Code Online (Sandbox Code Playgroud)
lastMonth = first - pd.Timedelta(months=3)
Run Code Online (Sandbox Code Playgroud)

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