首页 > 解决方案 > 从格式不一致的字符串中提取“年份”;AttributeError:“NoneType”对象没有属性“组”

问题描述

这是一个令人费解的问题,因此请在此处查看我的项目文件

我有一个如下的数据框,想从“事实”列中的字符串中提取“年份”(4 位数字)并将“年份”存储在“年份”列中。但是,“事实”列中的日期时间不遵循如下一致的格式。

Fact    Year
0   Population estimates, July 1, 2016, (V2016) NaN
1   Population estimates base, April 1, 2010, (V2...    NaN
2   Population, percent change - April 1, 2010 (es...   NaN
3   Population, Census, April 1, 2010   NaN
4   Persons under 5 years, percent, July 1, 2016, ...   NaN

我使用正则表达式定义了一个模式,并使用for 循环来提取 4 位数字,但是我收到了 AttributeError。代码和错误信息如下:

for row in range(0, 64):
    Year = re.search(pattern1, data.iat[row, index_fact]).group()
    data.iat[row, index_year] = Year
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-48-4d5d634f47d5> in <module>
      1 for row in range(0, 64):
----> 2     Year = re.search(pattern1, data.iat[row, index_fact]).group()
      3     data.iat[row, index_year] = Year

AttributeError: 'NoneType' object has no attribute 'group'

在结果表中,一些年份被成功提取,但其他年份没有:


Fact    Year
0   Population estimates, July 1, 2016, (V2016) 2016
1   Population estimates base, April 1, 2010, (V2...    2010
2   Population, percent change - April 1, 2010 (es...   2010
3   Population, Census, April 1, 2010   2010
4   Persons under 5 years, percent, July 1, 2016, ...   2016
... ... ...
59  Nonminority-owned firms, 2012   <re.Match object; span=(25, 29), match='2012'>
60  Veteran-owned firms, 2012   <re.Match object; span=(21, 25), match='2012'>
61  Nonveteran-owned firms, 2012    <re.Match object; span=(24, 28), match='2012'>
62  Population per square mile, 2010    <re.Match object; span=(28, 32), match='2010'>
63  Land area in square miles, 2010 <re.Match object; span=(27, 31), match='2010'>

请让我知道如何修复 AttributeError 或建议任何更好的方法来实现我的原始目标(即从字符串中提取“年份”。

非常感谢!

标签: pythonregexstringattributeerror

解决方案


你可以使用类似的东西datefinder

>>> s = "Population estimates, July 1, 2016"
>>> list(datefinder.find_dates(s))
[datetime.datetime(2016, 7, 1, 0, 0)]

应该让你的生活更轻松一点。


推荐阅读