python中最近九个月数据的自动提取

python中最近九个月数据的自动提取,python,pandas,datetime,Python,Pandas,Datetime,我有一个数据框架,它由在特定时间跨度内聚合的数据组成,其中一列是“日期”。现在,每天都有一个列完全相同的新数据添加到此聚合数据中。现在,我想对这些聚合数据应用一个过滤器,即添加新的每日数据的帖子,我只需要最近九个月的数据 假设df_old是聚合数据,而新数据是df_new。现在我是这样做的 #Append new data to old aggregated data with same columns df_old=df_old.append(df_new) df_old['date']=pd

我有一个数据框架,它由在特定时间跨度内聚合的数据组成,其中一列是“日期”。现在,每天都有一个列完全相同的新数据添加到此聚合数据中。现在,我想对这些聚合数据应用一个过滤器,即添加新的每日数据的帖子,我只需要最近九个月的数据

假设df_old是聚合数据,而新数据是df_new。现在我是这样做的

#Append new data to old aggregated data with same columns
df_old=df_old.append(df_new)
df_old['date']=pd.to_datetime(df_old['date'])
max_date=max(df_old['date']
df_old['date_diff']=(max_date - df_old['date'])
##Considering a calender month has 30 days and three months have 31 days
df_old.loc[df_old.date_diff <=273]
#将新数据附加到具有相同列的旧聚合数据
df_old=df_old.append(df_new)
df_old['date']=pd.to_datetime(df_old['date'])
max_date=max(df_old['date']
df_old['date_diff']=(最大日期-df_old['date'])
##考虑到日历月有30天,三个月有31天

df_old.loc[df_old.date_diff您可以动态生成6个月前的日期

from datetime import date
from dateutil.relativedelta import relativedelta

six_months_old = date.today() + relativedelta(months=-6)

six_months_old
#datetime.date(2016, 9, 5)
现在使用此值筛选数据帧

df_old = df_old.append(df_new)
df_old['date'] = pd.to_datetime(df_old['date'])
max_date = max(df_old['date']

result_df = df_old.loc[(df_old['date'] >= six_months_old)]
这里有一个更为“Pandaic”的解决方案:

数据:

解决方案:

In [42]: df.loc[df['Date'] > df['Date'].max() - pd.DateOffset(months=9)]
Out[42]:
         Date
5  2000-05-25
6  2000-06-23
7  2000-07-22
8  2000-08-20
9  2000-09-18
10 2000-10-17
11 2000-11-15
12 2000-12-14
13 2001-01-12
14 2001-02-10

谢谢Vikash!!…这就是我想要的…我想避免任何硬编码。@user2906657欢迎:)如果答案符合预期,请勾选答案。谢谢:)
In [42]: df.loc[df['Date'] > df['Date'].max() - pd.DateOffset(months=9)]
Out[42]:
         Date
5  2000-05-25
6  2000-06-23
7  2000-07-22
8  2000-08-20
9  2000-09-18
10 2000-10-17
11 2000-11-15
12 2000-12-14
13 2001-01-12
14 2001-02-10