【问题标题】:Apply multiple regex patterns in lambda expression在 lambda 表达式中应用多个正则表达式模式
【发布时间】:2019-10-23 01:44:54
【问题描述】:

我有一个相当复杂的问题,我想知道你们中的任何编码向导是否能够帮助我:p

我想通过一个 lambda 表达式使用两个正则表达式模式。
该代码应用于熊猫数据框的一列。

我们遍历列中的所有元素。如果字符串包含 '[' 方括号,则必须执行一个正则表达式模式。如果字符串不包含方括号,则必须执行其他正则表达式模式。

可以在下面找到两种有效的正则表达式模式。
目前它们是分开的,但我想将它们结合起来。

我有以下代码可以正常工作:

chunk['http'] = chunk.loc[chunk['Protocol'] == 'HTTP', 'Information'].apply(
                    lambda x: re.sub(r'\b[^A-Z\s]+\b', '', x))


chunk['http'] = chunk.loc[chunk['Protocol'] == 'HTTP', 'Information'].apply(
                lambda x: re.sub(r'\[(.*?)\]', '', x))

第一个表达式只保留 CAPS 中的值。第二个表达式只保留方括号之间的值。

我已经尝试在下一段代码中将它们结合起来:

chunk['http'] = chunk.loc[chunk['Protocol'] == 'HTTP', 'Information'].apply(
                    lambda x: re.sub(r'\b[^A-Z\s]+\b', '', x)) \
                    if '[' in x == False\
                    else re.sub(r'\[(.*?)\]', '', x)

但是这会返回以下错误:

NameError: free variable 'x' referenced before assignment in enclosing scope

【问题讨论】:

    标签: python regex pandas lambda


    【解决方案1】:

    你放错了括号。应该是

    chunk['http'] = chunk.loc[chunk['Protocol'] == 'HTTP', 'Information'].apply(
                        lambda x: re.sub(r'\b[^A-Z\s]+\b', '', x) \
                        if '[' in x == False\
                        else re.sub(r'\[(.*?)\]', '', x))
    

    【讨论】:

      【解决方案2】:

      Lambda 只是一个简短并返回值的函数。您可以改写您的函数 - def function_name(x) 在某处并在那里做比在 lambda 中更多的事情。只记得最后返回值!

      def function_name(x):
          x = re.sub(r'\b[^A-Z\s]+\b', '', x)) # lambda by default returns the value of the expression, here 
          #I really didn't understood your if/else block, but it should be here
          return re.sub(r'\[(.*?)\]', '', x) #last value, as opposed to lambda, should explicitly use return statement
      
      chunk['http'] = chunk.loc[chunk['Protocol'] == 'HTTP', 'Information'].apply(function_name)
      

      【讨论】:

      • 没想到,这些代码行的 lambda 表达式有点乱。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-16
      • 1970-01-01
      • 2012-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-08
      相关资源
      最近更新 更多