首页 > 解决方案 > 在 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

我知道我错过了一些东西。

有人可以建议如何根据条件有效过滤上述数据框吗?

标签: pythonpandas

解决方案


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

推荐阅读