我有一个非常复杂的问题,我想知道你们中的任何编码向导是否都能帮我忙: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
答案 0 :(得分: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))
答案 1 :(得分:1)
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)