Python 如何按月份和年份将一个数据帧划分为多个数据帧

Python 如何按月份和年份将一个数据帧划分为多个数据帧,python,pandas,python-2.7,dataframe,Python,Pandas,Python 2.7,Dataframe,我有一个具有不同列(如price、id、product和date)的数据框,我需要根据系统的当前日期(current_date=np.datetime64(date.today())将此数据框划分为几个数据框 例如,如果今天是2020-02-07,我想将我的主数据框分为三个不同的数据框,其中df1是最后一个月的数据(2020-01-07到2020-02-07的数据),df2是最后三个月的数据(不包括df1中已经存在的月份,因此更准确地说是2019-10-07到2020-01-07)df3将是留在

我有一个具有不同列(如price、id、product和date)的数据框,我需要根据系统的当前日期(current_date=np.datetime64(date.today())将此数据框划分为几个数据框

例如,如果今天是2020-02-07,我想将我的主数据框分为三个不同的数据框,其中df1是最后一个月的数据(2020-01-07到2020-02-07的数据),df2是最后三个月的数据(不包括df1中已经存在的月份,因此更准确地说是2019-10-07到2020-01-07)df3将是留在原始数据帧上的数据

有什么简单的方法可以做到这一点吗?此外,我一直在尝试使用Grouper,但我一再遇到此错误:NameError:名称“Grouper”未定义(我的Pandas版本为0.24.2)

您可以在最近1个月和3个月的日期时间使用,通过以下方式过滤:


@SarahKerrigan-我将-m1=df['date'].
m1=(df['date']>last1m)&(df['date']=last1m)&(df['date']last1m)&(df['date']last1m)
,如果需要一个间隔打开,一个间隔关闭是不可能的。
rng = pd.date_range('2019-10-10', periods=20, freq='5d')
df = pd.DataFrame({'date': rng, 'id': range(20)})  
print (df)
         date  id
0  2019-10-10   0
1  2019-10-15   1
2  2019-10-20   2
3  2019-10-25   3
4  2019-10-30   4
5  2019-11-04   5
6  2019-11-09   6
7  2019-11-14   7
8  2019-11-19   8
9  2019-11-24   9
10 2019-11-29  10
11 2019-12-04  11
12 2019-12-09  12
13 2019-12-14  13
14 2019-12-19  14
15 2019-12-24  15
16 2019-12-29  16
17 2020-01-03  17
18 2020-01-08  18
19 2020-01-13  19
current_date = pd.to_datetime('now').floor('d')
print (current_date)
2020-02-07 00:00:00

last1m = current_date - pd.DateOffset(months=1)
last3m = current_date - pd.DateOffset(months=3)

m1 = (df['date'] > last1m) & (df['date'] <= current_date)
m2 = (df['date'] > last3m) & (df['date'] <= last1m)
#filter non match m1 or m2 masks
m3 = ~(m1 | m2)

df1 = df[m1]
df2 = df[m2]
df3 = df[m3]
print (df1)
         date  id
18 2020-01-08  18
19 2020-01-13  19

print (df2)
         date  id
6  2019-11-09   6
7  2019-11-14   7
8  2019-11-19   8
9  2019-11-24   9
10 2019-11-29  10
11 2019-12-04  11
12 2019-12-09  12
13 2019-12-14  13
14 2019-12-19  14
15 2019-12-24  15
16 2019-12-29  16
17 2020-01-03  17

print (df3)
        date  id
0 2019-10-10   0
1 2019-10-15   1
2 2019-10-20   2
3 2019-10-25   3
4 2019-10-30   4
5 2019-11-04   5