首页 > 解决方案 > 从今天起提前六个月或之前对数据进行子集化 pandas

问题描述

我有一个如下所示的数据框

Unit_ID    Added_Date                   Status         
105        2019-10-02 08:14:16          Rented
106        2020-10-21 07:19:13          Rented
109        2020-03-02 07:18:19          Rented
108        2020-08-01 04:15:28          Vacant
100        2014-10-02 08:14:16          Rented

从上面的数据中,我想根据 Additional_Date 列过滤从今天起提前六个月或之前的数据。

预期输出:

Unit_ID    Added_Date                   Status         
105        2019-10-02 08:14:16          Rented
109        2020-03-02 07:18:19          Rented
100        2014-10-02 08:14:16          Rented

标签: pandaspandas-groupby

解决方案


使用Series.betweenwithoffsets.DateOffset过滤boolean indexing

today = pd.to_datetime('now').floor('d')
offset = pd.offsets.DateOffset(months=6)

df = df[df['Added_Date'].between(today - offset, today + offset)]
print (df)
   Unit_ID          Added_Date  Status
0      105 2019-10-02 08:14:16  Rented
2      109 2020-03-02 07:18:19  Rented

对于今天之前的未来 6 个月之前的过滤数据,请使用:

today = pd.to_datetime('now').floor('d')
offset = pd.offsets.DateOffset(months=6)
df1 = df[df['Added_Date'] <= today + offset]
print (df1)
   Unit_ID          Added_Date  Status
0      105 2019-10-02 08:14:16  Rented
2      109 2020-03-02 07:18:19  Rented
4      100 2014-10-02 08:14:16  Rented

推荐阅读