从格式不一致的字符串中提取'Year';属性错误:'NoneType'对象没有属性'group'



这是一个复杂的问题,所以请在这里查看我的项目文件

我有一个如下所示的数据帧,我想从"事实"列中的字符串中提取"年份"(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

我使用regex定义了一个模式,并使用for loop提取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或建议任何更好的方法来实现我的原始目标(即从字符串中提取"年份"。

非常感谢!

您可以使用类似datefinder的东西。

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

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

我会在这里使用str.extract和适当的正则表达式模式:

df["Year"] = df["Fact"].str.extract(r'bw+ d+, (d{4})b')

对于常规Python,请使用re.findall:

years = re.findall(r'bw+ d+, (d{4})b', fact)

最新更新