List Comprehension is not None AttributeError: 'NoneType' object has no attribute 'group'

List Comprehension is not None AttributeError: 'NoneType' object has no attribute 'group'

Date,Amount,Subcategory,Memo,
29/10/2021,953.76,DIRECTDEP,Stripe Payments UK    STRIPE       BGC,
29/10/2021,-1260.44,FT,DIESEL INJECTORS U    TRANSFER          FT,
29/10/2021,-509.15,FT,TNT                   002609348          FT,

以上是我需要分组的一些账户数据,稍后应用标签。

首先我尝试了这个df['Suppliers'] = [re.search(r'\b[a-zA-Z]{3,}\b', item).group(0) for item in df['Memo'] if item is not None]

但是得到AttributeError: 'NoneType' object has no attribute 'group'我理解这是因为在数据中没有找到模式

所以我尝试删除 .group(0) 并分别为每个项目获取匹配对象,例如 <re.Match object; span=(0, 6), match='Stripe'>

问题:我不确定为什么 if item is not None 不跳过那些没有找到匹配项的项目。为什么如果我返回一个我无法使用 .group(0)

访问的匹配对象

我已经找到了一个循环解决方案,但我真的很想了解列表组合方法的问题所在。


for item in df['Memo']:
    match = re.search(r'\b[a-zA-Z]{3,}\b', item)
    try:
        my_list.append(match.group(0).lower())
        df['Suppliers'] = pd.DataFrame({'Suppliers': my_list})
    except AttributeError:
        my_list.append('na')
        continue

当您使用 if item is not None 时,您检查 item 是否不是 None,而不是 re.search(r'\b[a-zA-Z]{3,}\b', item) 的结果操作。

直接用Series.str.extract即可:

df['Suppliers'] = df['Memo'].str.extract(r'\b([a-zA-Z]{3,})\b')

请注意,当您想与 Series.str.extract.

一起使用时,需要使用一对未转义的括号在模式中形成捕获组

如果要在未找到匹配项的情况下将 na 添加为字符串,请添加 .fillna:

df['Suppliers'] = df['Memo'].str.extract(r'\b([a-zA-Z]{3,})\b').fillna('na')