非常感谢您今天提出的问题。
我下面有一个df enter image description here
您会看到值
列中有字典类型值
列中的这些字典具有三个键优惠ID,offer_id和交易
我尝试创建一个新列,该列从offer id和offer_id中获取值
我尝试在其中使用lambda,但失败
test2['test'] = transcript.value.apply(lambda x: list(x.values())[0] if (list(x.keys())[0] in ['offer id', 'offer_id']) )
只是想知道为什么它总是说“ SyntaxError:无效的语法”。
再次感谢您的帮助!
-------------------解决方案--------------------
感谢大家的帮助
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语句有效...
最佳
答案 0 :(得分:0)
在表达式中使用with
时,您必须也写一个import mysql.connector
connection = mysql.connector.connect(
host=host,
user=user,
password=password
)
cursor = connection.cursor()
with open(script, encoding="utf-8") as f:
commands = f.read().split(';')
for command in commands:
cursor.execute(command)
print(command)
connection.close()
子句。例如:
if
原因是表达式应该产生一个值,因此表达式else
毫无意义,除非您说明两种情况下的结果都应该是什么。如果您不说条件为false时结果应该是什么,那么在这种情况下表达式将不会产生值。
因此,您的代码存在语法错误,因为您没有写>>> 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
不在else
中时的结果。
答案 1 :(得分:0)
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?')