python - 在 Pandas 中使用条件动态过滤基于数据框的日期
问题描述
我正在尝试根据日期字段过滤数据框。
Date Value
201810 100
201811 150
201812 95
201901 125
201902 150
201903 200
201904 225
过滤是动态完成的。例如,第一个日期和结束日期不应该是“硬编码”。所以我的方法如下:
month = pd.DataFrame(set(df['Date']),columns=['Date'])
df['Date'] = pd.to_datetime(df['Date'],format='%Y%m)
从这里开始,我必须根据日期进行过滤并创建一个新的数据框。在这是最后一个日期,比如 201903。
dt_first = month['Date'].head(1) <---first date is being dynamically created
dt_last = month.iloc[-2] <-- last date, dynamically created.
df_filter = df[(df.Date.ge(dt_first))&(df.Date.le(dt_last))]
但最后一行是生成一个空白数据框。结果数据框应如下所示
Date Value
201810 100
201811 150
201812 95
201901 125
201902 150
201903 200
我知道我错过了一些东西。
有人可以建议如何根据条件有效过滤上述数据框吗?
解决方案
Here is necessary compare by scalar, so is extracted first and last value of column by Series.iat
:
Btw, if compare by ge
for greater or equal in sorted values with first val it match all data, so this condition always return Trues, so should be removed with same output:
df['Date'] = pd.to_datetime(df['Date'],format='%Y%m')
df_filter = df[(df.Date.ge(df['Date'].iat[0]))&(df.Date.lt(df['Date'].iat[-1]))]
Same like:
df_filter = df[(df.Date.lt(df['Date'].iat[-1]))]
print (df)
Date Value
0 2018-10-01 100
1 2018-11-01 150
2 2018-12-01 95
3 2019-01-01 125
4 2019-02-01 150
5 2019-03-01 200
6 2019-04-01 225
推荐阅读
- flutter - 颤振医生致命,未知修订或路径不在工作树错误中
- android-sdk-tools - UI automator 文件未包含在所有 SDK 工具的最新 AndroidStuio 或 ZIP 文件中
- vb.net - VB.Net DataGridView手动用户输入数据保存到XML给出错误:对象引用未设置为对象的实例
- c - 明确告诉 GCC 9.2 取消切换循环以允许自动矢量化
- java - 我如何使用 Java Stream 来减少这种类结构?
- hibernate - JPA实体中具有复合主键的表的基于条件的序列生成
- wpf - 如何在我的文本框 WPF 中获取短日期格式
- algorithm - 用于位置比较的 alpha beta 剪枝算法
- scala - Spark Scala - 从另一个视图中选择日期和日期 + 24 小时之间的所有记录
- r - 如何使用 R/传单在地图中绘制单个数据点?