【问题标题】:Applying regex to dataframe column based on value in another column根据另一列中的值将正则表达式应用于数据框列
【发布时间】: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


【解决方案1】:

您可以zip 列,然后即时构建正则表达式:

df['colB'] = [regex_func('(?i)(?<=' + y + ' )[^ ]+', x)
              for x, y in zip(df['colA'], df['col1'])]

【讨论】:

  • 看起来这对我有用。我唯一添加的是一个 re.compile(),它围绕着我传递给 regex_func 的内容。谢谢!!
猜你喜欢
  • 2019-02-21
  • 2018-08-06
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
  • 2018-09-24
  • 2020-10-06
  • 2020-05-23
  • 1970-01-01
相关资源
最近更新 更多