Can someone please help me identify the missing piece to execute this code?

Question:

I am trying to establish a categorical variable with the Term column in my dataset. I want RealEstate to = 1 if the Term is =< 240 and RealEstate to = 0 if the Term is > 240, but I keep getting an invalid syntax error. Help please.

enter image description here

Asked By: DopeNAnalytical

||

Answers:

Let’s break down this statement:

RealEstate is 1 if 'Term' >= 240 and RealEstate is 0 if 'Term' <240

The overall construct you’re trying to use here, called a ternary conditional, is x if y else z. The first problem is that you’ve constructed it as (x if y) and (p if q).

As a basic operation, Python can’t understand x if y, it can only understand x if y else z or:

if x:
    y

The second issue you have is a bit subtler, and with is. RealEstate is 1 first evaluates the variable RealEstate and then the variable 1. 1 is straightforward, and RealEstate could be an arbitrary value. If it is not equal to 1, then this will evaluate as True. It won’t set the value of RealEstate to 1.

Finally, 'Term' is a string and not a variable. It can’t be compared with 240, which is a number. So even if you fix the problems above, you’ll run into this as well. You’ll need to get the value of 'Term' from somewhere as a variable that can be compared to 240.

Answered By: Nathaniel Ford
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.