【问题标题】:extracting dates using Regex in python在python中使用正则表达式提取日期
【发布时间】:2019-07-17 21:59:40
【问题描述】:

我想从我的数据框列 data3['CopyRight'] 中提取年份。

CopyRight
2015 Sony Music Entertainment
2015 Ultra Records , LLC under exclusive license
2014 , 2015 Epic Records , a division of Sony Music Entertainment
Compilation ( P ) 2014 Epic Records , a division of Sony Music Entertainment
2014 , 2015 Epic Records , a division of Sony Music Entertainment
2014 , 2015 Epic Records , a division of Sony Music Entertainment

我正在使用下面的代码来提取年份:

data3['CopyRight_year'] = data3['CopyRight'].str.extract('([0-9]+)', expand=False).str.strip()

使用我的代码,我只能得到第一次出现的年份。

CopyRight_year
2015
2015
2014
2014
2014
2014

我想提取列中提到的所有年份。

预期输出

CopyRight_year
    2015
    2015
    2014,2015
    2014
    2014,2015
    2014,2015

【问题讨论】:

    标签: python regex pandas dataframe


    【解决方案1】:

    findall 与正则表达式一起使用以查找所有长度为4 的整数到列表中,并通过分隔符最后join

    感谢@Wiktor Stribiżew 的想法添加字边界r'\b\d{4}\b'

    data3['CopyRight_year'] = data3['CopyRight'].str.findall(r'\b\d{4}\b').str.join(',')
    print (data3)
                                               CopyRight CopyRight_year
    0                      2015 Sony Music Entertainment           2015
    1   2015 Ultra Records , LLC under exclusive license           2015
    2  2014 , 2015 Epic Records , a division of Sony ...      2014,2015
    3  Compilation ( P ) 2014 Epic Records , a divisi...           2014
    4  2014 , 2015 Epic Records , a division of Sony ...      2014,2015
    5  2014 , 2015 Epic Records , a division of Sony ...      2014,2015
    

    【讨论】:

    • 我会使用r'\b\d{4}\b',因为'(\d{4})' 将匹配4位数的块,即使在较长的数字块中(例如006789中的0067)。
    • @jezrael - 非常感谢,我得到了预期的输出。
    【解决方案2】:

    您当前的正则表达式将只捕获数字,如果您想捕获逗号分隔的年份,那么您需要将您的正则表达式增强到这一点,

    [0-9]+(?:\s+,\s+[0-9]+)*
    

    这个正则表达式[0-9]+ 将匹配数字,另外(?:\s+,\s+[0-9]+)* 正则表达式将匹配一个或多个空格,后跟一个逗号,再后跟一个或多个空格,最后是一个数字和整个数字零次或多次在数据中可用。

    Demo

    将您的熊猫数据框行更改为此,

    data3['CopyRight_year'] = data3['CopyRight'].str.extract('([0-9]+(?:\s+,\s+[0-9]+)*)', expand=False).str.replace('\s+','')
    

    打印,

                                               CopyRight CopyRight_year
    0                      2015 Sony Music Entertainment           2015
    1   2015 Ultra Records , LLC under exclusive license           2015
    2  2014 , 2015 Epic Records , a 1999 division of ...      2014,2015
    3  Compilation ( P ) 2014 Epic Records , a divisi...           2014
    4  2014 , 2015 Epic Records , a division of Sony ...      2014,2015
    5  2014 , 2015 Epic Records , a division of Sony ...      2014,2015
    

    虽然我喜欢 jezrael 的答案,它使用了 findalljoin,这为您提供了更大的灵活性和更简洁的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      • 2019-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多