[英]pandas filter dates to last most recent 3 months
I want to filter a pandas data frame to the last most recent 3 months. 我想将熊猫数据框过滤到最近的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]
This snippet sort of already works, but has the length of a month hard coded to 30 days. 这种代码段已经可以使用,但是将一个月的长度硬编码为30天。 How can I use a
pd.Timedelta('-3 month')
(which does not seem to work like this) to achieve a more robust function? 我如何使用
pd.Timedelta('-3 month')
(似乎不起作用)来实现更强大的功能?
I think you need offsets
, because Timedelta
only does not work with months: 我认为您需要
offsets
,因为Timedelta
仅在几个月内不起作用:
lastMonth = first - pd.offsets.MonthBegin(3)
#lastMonth = first - pd.offsets.relativedelta(months=3)
lastMonth = first - pd.Timedelta(months=3)
ValueError: cannot construct a Timedelta from the passed arguments, allowed keywords are [weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds]
ValueError:无法根据传递的参数构造Timedelta,允许的关键字为[周,日,小时,分钟,秒,毫秒,微秒,纳秒]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.