首页 > 解决方案 > 如何按月和年将熊猫数据框划分为多个数据框

问题描述

我有一个包含不同列(如价格、id、产品和日期)的数据框,我需要根据系统的当前日期(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: name 'Grouper' is not defined (my Pandas version is 0.24.2)

标签: pythonpandaspython-2.7dataframe

解决方案


您可以使用offsets.DateOffset过去 1 个月和 3 个月的日期时间,按以下方式过滤boolean indexing

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

推荐阅读