【发布时间】:2020-03-20 20:23:21
【问题描述】:
我在下面有这个 regex_func 辅助函数,它可以很好地使用 map 和 lambda 从 df 列中提取匹配项。
def regex_func(regex_compile,x,item=0,return_list=False):
"""Function to handle list returned by re.findall()
Takes the first value of the list.
If empty list, returns empty string"""
match_list = regex_compile.findall(x)
if return_list:
match = match_list
elif match_list:
try:
match = match_list[item]
except:
match = ""
else:
match = ""
return match
#Working example
regex_1 = re.compile('(?i)(?<=\()[^ ()]+')
df['colB'] = df['colA'].map(lambda x: regex_func(regex_1, x))
我在执行类似任务时遇到了麻烦。我希望正则表达式基于另一列中的值,然后应用。我尝试的一种方法不起作用:
# Regex should be based on value in col1
# Extracting that value and prepping to input into my regex_func()
value_list = df['col1'].tolist()
value_list = ['(?i)(?<=' + d + ' )[^ ]+' for d in value_list]
value_list = [re.compile(d) for d in value_list]
# Adding prepped list back into df as col2
df.insert(1,'col2',value_list)
#Trying to create col4, based on applying my re.compile in col 2 to a value in col3.
df.insert(2,'col4', df['col3'].map(lambda x: df['col2'],x)
我明白为什么上述方法不起作用,但一直无法找到解决方案。
【问题讨论】:
-
您可以提供一些示例数据吗?否则将无法看到它为什么不起作用....
-
看起来 a_guest 的回答对我有用!谢谢
标签: python regex pandas dataframe