【问题标题】:Drop rows based on date condition根据日期条件删除行
【发布时间】:2019-12-13 06:59:39
【问题描述】:

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

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

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

这是一个示例 DataFrame:

>>> 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

drop 后的预期 DataFrame 应该是:


    YearMonth
0   2014-09
1   2014-10

【问题讨论】:

  • 你能发布一个示例数据框吗?
  • 抱歉,我是这个平台的新手。怎么发?
  • 尝试pandas.to_datetime(new.YearMonth) > datetime(2020,05) ...请注意,它可能会排除当月第一天(而不是月底)之后的任何日期
  • 欢迎来到 StackOverflow。请花时间阅读how to provide a great pandas example 上的这篇文章以及如何提供minimal, complete, and verifiable example 并相应地修改您的问题。 how to ask a good question 上的这些提示也可能有用。
  • 我已根据我的理解编辑了您的问题。如果符合您的预期,请审核并批准

标签: python pandas dataframe date rows


【解决方案1】:

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

from datetime import datetime as dt

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

【讨论】:

    【解决方案2】:

    我认为您希望 boolean indexing 将 > 更改为 <= 所以按月比较工作得很好:

    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
    

    在最新版本的 pandas 中也可以使用字符串比较:

    df = new[new.YearMonth <= '2020-05']
    

    【讨论】:

    • 转换时出错。 不能转换为日期时间
    • @SpandanRout - 你现在可以测试了吗?
    • 显然 YYYY-MM 不是日期时间格式,而是一个对象。并且在转换它时会像之前一样显示一条错误消息,在测试最近的代码时它显示了这个错误:TypeError: Cannot compare type 'Period' with type 'str'
    • @SpandanRout - 你现在可以测试了吗?
    猜你喜欢
    • 1970-01-01
    • 2020-09-03
    • 2021-09-21
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 2018-03-03
    相关资源
    最近更新 更多