Reputation: 4228
I'm getting a SyntaxError
for:
housing['Lot Area'].apply(lambda x: x + 50000 if x > 20000)
When I add else
, the code runs fine:
housing['Lot Area'].apply(lambda x: x + 50000 if x > 20000 else x)
Does if
only work in combination with else
here? I'd like to increment x
with 50000 only if x > 20000
-- otherwise I'd like x
to remain unchanged. I find the else
part a bit redundant here. Besides the first question before, is there any way to write this code without the else
part?
Upvotes: 0
Views: 44
Reputation: 323226
Base on your description , even apply
is not need here
housing.loc[housing['Lot Area']>20000,'Lot Area']+=50000
Comment from Alex :
if the if statement resolves to False for a value, then apply() doesn't return and just lets the value in the Series as it is
Upvotes: 4
Reputation: 9946
you're getting a SyntaxError
because you are typing invalid syntax. the ternary operator must be used like
expression if bool else other_expression
Upvotes: 1