在pandas.apply中使用lambda函数时出现“SyntaxError:无效语法”

2024-05-16 08:20:07 发布

您现在位置:Python中文网/ 问答频道 /正文

谢谢你今天帮我提问题

我有一个像下面这样的df enter image description here

如您所见,列值中有dict type

值列中有三个dict键

报价id、报价id和交易

我尝试创建一个新列,从offer id和offer\u id获取值

我试着用lambda,但失败了

test2['test'] = transcript.value.apply(lambda x: list(x.values())[0] if (list(x.keys())[0] in ['offer id', 'offer_id']) )

只是想知道为什么它总是说“SyntaxError:invalid syntax”

再次感谢你的帮助

--------解决方案------------------

谢谢你们的帮助

test1['test'] = test1.value.apply(lambda x: list(x.values())[0] if (list(x.keys())[0] in ['offer id', 'offer_id']) else np.NaN)

正在添加else语句,它可以工作

最好的


Tags: lambdaintestidifvaluekeyselse
2条回答

test2['test'] = transcript.value.apply(lambda x: list(x.values())[0] if (list(x.keys())[0] in ['offer id', 'offer_id']) else 'what do you want x to be if the if statement is not fulfilled?')

在表达式中使用if时,也必须编写else子句。例如:

>>> x = 5
>>> 1 if x > 0 else 0
1
>>> 1 if x > 0
  File "<stdin>", line 1
    1 if x > 0
             ^
SyntaxError: invalid syntax

原因是一个表达式应该产生一个值,所以表达式中的if没有意义,除非你说在这两种情况下结果应该是什么。如果在条件为false时没有说明结果应该是什么,那么表达式在这种情况下不会产生值

因此,您的代码有一个语法错误,因为您没有编写else来说明当list(x.keys())[0]不在['offer id', 'offer_id']中时结果应该是什么

相关问题 更多 >