【问题标题】:List Comprehension is not None AttributeError: 'NoneType' object has no attribute 'group'List Comprehension is not None AttributeError: 'NoneType' object has no attribute 'group'
【发布时间】:2021-11-03 13:12:08
【问题描述】:
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]

但是getAttributeError: 'NoneType' object has no attribute 'group'我明白这是因为在数据中找不到模式。

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

问题:我不知道为什么if item is not None 不会跳过那些找不到匹配项的项目。以及为什么如果我返回一个我无法使用.group(0) 访问的匹配对象

我已经找到了一个带有循环的解决方案,但我真的很想了解 list comp 方法的问题所在。


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

【问题讨论】:

    标签: python regex error-handling list-comprehension


    【解决方案1】:

    当您使用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')
    

    【讨论】:

    • 谢谢!那太棒了!如果找不到匹配项会怎样?它只是忽略它?
    • @MartyHewing 默认情况下你会得到np.NaNs,但你可以像我的回答一样使用filllna
    • @MartinHewing 抱歉,我在fillna 中打错了字。新键盘,你知道?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 2017-10-20
    • 2022-01-10
    • 2022-01-10
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多