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

Time:08-24

Update: Thank you to those who attempted to help without negativity; I appreciate it, I am going to continue trying to debug independently, no negativity :) Again, thanks to those who are trying to help without negativity.

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.

CodePudding user response:

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.

  • Related