我有一个非常简单的搜索字符串。我在找一家叫“Lidl”的商店
我的数据帧:
term_location amount
0 Lidl 2.28
1 Lidl 16.97
2 Lidl 2.28
3 Lidl 16.97
4 Lidl 16.97
5 Lidl 16.97
6 Lidl 16.97
7 Lidl 16.97
8 Lidl 16.97
9 Lidl 16.97
这里我正在搜索Lidl的正则表达式版本:
r = r'\blidl\b'
r = re.compile(r)
df[df.term_location.str.contains(r,re.IGNORECASE,na=False)]
这将返回一个空的数据帧
但是,如果我只是将简单字符串放在str.contains()
中,它就工作了,并且我得到了返回的LIDL的数据帧:
df[df.term_location.str.contains('lidl',case=False,na=False)]
我希望能够使用regex,因为我还有一些条件要构建到查询中
发生了什么事?我想不出来
为pd.DataFrame.from_dict()
练习数据帧:
{'term_location': {0: 'Lidl',
1: 'Lidl',
2: 'Lidl',
3: 'Lidl',
4: 'Lidl',
5: 'Lidl',
6: 'Lidl',
7: 'Lidl',
8: 'Lidl',
9: 'Lidl'},
'amount': {0: 2.28,
1: 16.97,
2: 2.28,
3: 16.97,
4: 16.97,
5: 16.97,
6: 16.97,
7: 16.97,
8: 16.97,
9: 16.97}}
您的正则表达式无法工作,因为您正在尝试完全匹配单词“lidl”(小写)
您应该将单词的第一个字符改为大写:
或者使用
re.IGNORECASE
标志来匹配单词,而不管其大小写:请记住
\b
试图匹配文本开头的单词。例如,“_Lidl”与上面的任何正则表达式都不匹配使用字符串文字作为模式参数,它将被解析为正则表达式:
case=False
的作用与re.IGNORECASE
相同或者,使用
(?i)
:相关问题 更多 >
编程相关推荐