I have the following code that attempts to run a lambda function with a string that contains a condition. Problem is that I get an error when running the function.
df = pd.DataFrame({
'height': [1, 2, 3, 4, 5],
'weight': [10, 20, 30, 40, 50]
})
s = "if obj.height > 2: \
obj.weight \
else: \
obj.weight * 2"
df['new_status'] = df.apply(lambda obj: eval(s), axis=1)
the error is
if obj.height > 2: obj.weight else: obj.weight * 2
^ SyntaxError: invalid syntax
How to fix this to make it work?