【发布时间】: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