我有一个DataFrame'df'和一个字符串'l'列表 . 我想迭代列表,找到与列表中的字符串匹配的DataFrame行 . 如果列表元素中没有括号,则以下代码可以正常工作 . 似乎正则表达式没有正确定义,并且不知何故双括号不匹配 .
import pandas as pd
import re
d = {'col1': ['100-(abc)','qwe-100-(abc)', '100-(abc)1',
'xyz', 'xyz2', 'zzz'],
'col2': ['100', '1001','200', '300', '400', '500']}
df = pd.DataFrame(d)
lst = ['100-(abc)', 'xyz']
for l in lst:
print("======================")
pattern = re.compile(r"(" + l + ")$")
print(df[df.col1.str.contains(pattern, regex=True)])
结果:
======================
Empty DataFrame
Columns: [col1, col2]
Index: []
======================
col1 col2
3 xyz 300
Expected result:
======================
col1 col2
0 100-(abc) 100
1 qwe-100-(abc) 1001
======================
col1 col2
3 xyz 300
2 回答
你需要明白:
如果要在正则表达式中使用任何这些字符作为文字,则需要使用反斜杠转义它们 . 如果你想匹配
1+1=2
,正确的正则表达式是1\+1=2
. 否则,加号具有特殊含义 . 与括号相同,如果你想匹配(abc)
,你必须做\(abc\)
输出:
只需使用isin
编辑:与isin一起添加正则表达式模式
你得到