谢谢你今天帮我提问题
我有一个像下面这样的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语句,它可以工作
最好的
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
子句。例如:原因是一个表达式应该产生一个值,所以表达式中的
if
没有意义,除非你说在这两种情况下结果应该是什么。如果在条件为false时没有说明结果应该是什么,那么表达式在这种情况下不会产生值因此,您的代码有一个语法错误,因为您没有编写
else
来说明当list(x.keys())[0]
不在['offer id', 'offer_id']
中时结果应该是什么相关问题 更多 >
编程相关推荐