根据日期条件删除行

时间:2019-12-13 06:59:39

标签: python pandas dataframe date rows

我有一个名为new的Pandas DataFrame,其中YearMonth列的日期格式为YYYY-MM。我想根据以下条件删除行:如果日期超出“ 2020-05”。我尝试使用此:

new = new.drop(new[new.YearMonth>'2020-05'].index)

,但无法显示语法错误“无效令牌”。

这是一个示例数据框:

>>> new = pd.DataFrame({
    'YearMonth': ['2014-09', '2014-10', '2020-09', '2021-09']
})
>>> print(new)
    YearMonth
0   2014-09
1   2014-10
2   2020-09
3   2021-09

删除后的预期DataFrame应该是:


    YearMonth
0   2014-09
1   2014-10

2 个答案:

答案 0 :(得分:1)

只需将其转换为日期时间,然后将其格式化为月份并将其子集化即可。

from datetime import datetime as dt

new['YearMonth']=pd.to_datetime(new['YearMonth']).dt.to_period('M')
new=new[~(new['YearMonth']>'2020-05')]

答案 1 :(得分:0)

我认为您希望将>更改为<=的{​​{3}},所以按月份比较效果很好:

new = pd.DataFrame({
    'YearMonth': pd.to_datetime(['2014-09', '2014-10', '2020-09', '2021-09']).to_period('m')
})
print (new)
  YearMonth
0   2014-09
1   2014-10
2   2020-09
3   2021-09

df = new[new.YearMonth <= pd.Period('2020-05', freq='m')]
print (df)
  YearMonth
0   2014-09
1   2014-10

在最新版本的熊猫中,还可以通过字符串进行比较:

df = new[new.YearMonth <= '2020-05']
相关问题