pandas - 从今天起提前六个月或之前对数据进行子集化 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
解决方案
使用Series.between
withoffsets.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
推荐阅读
- angularjs - 在表格分页上保留更改的数据 - AngularJS
- html - 在 svg 代码中包含文本的最佳方式是什么?
- spring-boot - 验证用户没有用户名和密码,但在春天使用令牌
- jquery - 标记拖出多边形时发出警报
- ruby - Ruby:单例类真的拥有匿名类吗?
- python - 如何避免 django 1.11 和 redis 3.0 上的缓存错误
- javascript - 将对象变量名称分配给变量 javascript 或 typescript
- javascript - Javascript通知功能但没有输出文本
- javascript - 在桌面网站中显示移动网站
- php - Composer Require florianv/swap 要求未满足