将列与自己的正则表达式匹配在另一列Python中 [英] Match column with its own regex in another column Python
本文介绍了将列与自己的正则表达式匹配在另一列Python中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在另一列中将数据列与其自己的正则表达式匹配.这是它的样子.
How to match data column with its own regex in another column. Here is how it looks like.
Data Regex
0 HU13568812 ^HU[0-9]{8}
1 78567899 ^NO[0-9]{5}
2 AT1234567 ^HU[0-9]{7}
如果输出匹配(1)或不匹配(0),则输出将是结果的新列.
The output will be a new column for the result if its match (1) or not match (0) like this.
Data Regex Match
0 HU13568812 ^HU[0-9]{8} 1
1 78567899 ^NO[0-9]{5} 0
2 AT1234567 ^AT[0-9]{7} 1
我尝试使用re.match(),但似乎无法一次使它与整行匹配.有没有更好的方法可以通过简单的函数或更多的pythonic方式来做到这一点?谢谢.
I tried to use re.match() but I can't seem to get it match for the whole row at once. Is there any better way to do this in a simple function or more pythonic way? Thank you.
推荐答案
一种方法是使用列表理解:
One way is to use list comprehension:
import re
df["Match"] = [1 if re.search(fr"{pat}", data) else 0
for data, pat in zip(df["Data"],df["Regex"])]
print (df)
Data Regex Match
0 HU13568812 ^HU[0-9]{8} 1
1 78567899 ^NO[0-9]{5} 0
2 AT1234567 ^AT[0-9]{7} 1
这篇关于将列与自己的正则表达式匹配在另一列Python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文