【问题标题】:Date regex filter with pandas not working带有熊猫的日期正则表达式过滤器不起作用
【发布时间】:2020-03-14 06:01:45
【问题描述】:

我的 DF 列中有信用卡到期日期(格式 = mm/yy) 我希望获得将在 mm/25(年 = 2025)后到期的卡

我正在尝试使用正则表达式来过滤意甲,但它出错了

我测试了一些正则表达式来了解被过滤的内容,我得到了这个

df.Exp_Date.filter(regex='.+') --> recognize all dates
df.Exp_Date.filter(regex='.+\/') --> return empty list 
df.Exp_Date.filter(regex='.+\/.+') --> return empty list

df.Exp_Date.filter(regex='\w+') --> recognize all dates (ok)
df.Exp_Date.filter(regex='\w+\/') --> return empty list
df.Exp_Date.filter(regex='\w+\/\w+') --> return empty list

我的问题可能在 / 字符上。我在 regexpal 上测试了所有正则表达式,它在那里工作,但在我的过滤器上没有。

【问题讨论】:

    标签: python regex pandas date


    【解决方案1】:

    你能用 contains 代替吗:

    df1
    #Out[472]: 
    #   Name   Date    OPP    Result
    #0  Will  11/20   @DAL  L110-102
    #1  Bill  11/25   @POR  W114-106
    #2  Bill  11/24   @LAC    L98-88
    #3  Mark  11/25   @LAL  W113-104
    #4   Sam  11/25    @NO  W122-104
    #5  Dude   9/24  vsSAC  W124-120
    #6  What   8/23   @MIL  L115-105
    
    df1[df1.Date.str.contains('/25')]                                                                                                                                                                 
    #Out[473]: 
    #   Name   Date   OPP    Result
    #1  Bill  11/25  @POR  W114-106
    #3  Mark  11/25  @LAL  W113-104
    #4   Sam  11/25   @NO  W122-104
    
    

    【讨论】:

      【解决方案2】:

      尝试像这样制作正则表达式字符串原始字符串: 正则表达式=r'.+/.+',而不是正则表达式='.+/.+'

      使用原始字符串的原因是当您使用转义字符(反斜杠)时,python 对它的解释与正则表达式不同。使用原始字符串可以防止这种情况。

      这里有一个更好的解释: What exactly is a "raw string regex" and how can you use it?

      【讨论】:

      • 有相同的输出,我将搜索更多关于正则表达式以了解发生了什么
      猜你喜欢
      • 2017-06-18
      • 2021-06-11
      • 1970-01-01
      • 2020-02-15
      • 2016-12-31
      • 2021-08-22
      • 2016-03-18
      • 2017-02-19
      • 1970-01-01
      相关资源
      最近更新 更多