3

I'm working with some county level data for the 2016 US Election.

I'm trying to calculate a blank Text field "Winner" based on two numeric fields "votes_dem" and "votes_gop" where it will take the greater of the two values in the numeric fields and input either "Trump" or "Clinton" into the new Winner field.

When I try to run my code block it returns with this warning:

WARNING 002858: Certain rows set to NULL due to error while evaluating Python expression: File "", line 2, in Reclass

I think there's a problem with my syntax, or just the way I'm trying to do it in general (still learning Python)

Wnner = Reclass(!Winner!)

def Reclass(Winner):
    if (votes_gop > votes_dem):
        return Trump
    elif (votes_dem > votes_gop):
        return Clinton

1 Answer 1

2

Edited to reflect @Vince's comment which is correct. Firstly, you need to pass the gop and dem votes into the function. Also, you're trying to return a string in your function but haven't enclosed it in quotes.

Try the following:

def Reclass(votes_gop, votes_dem):
    if (votes_gop > votes_dem):
        return "Trump"
    elif (votes_dem > votes_gop):
        return "Clinton"

further, for completeness, you may want to add the case when votes are equal.

def Reclass(votes_gop, votes_dem):
        if (votes_gop > votes_dem):
            return "Trump"
        elif (votes_dem > votes_gop):
            return "Clinton"
        else:
            return "Tie"

Also, this assumes you have valid values for all records in the votes_gop and votes_dem fields. If any of them are Null, you may run into problems.

Also, I just noticed that you're first line has Wnner instead of Winner.

Invocation of the function should be:

Reclass(!votes_gop!,!votes_dem!)
3
  • Odds are, the function prototype should be def winner(votes_gop,votes_dem) and invoked with winner(!votes_gop!,!votes_dem!)
    – Vince
    Commented May 15, 2020 at 0:35
  • You're absolutely right, @Vince. I've edited to reflect this.
    – Fezter
    Commented May 15, 2020 at 1:05
  • Just came back to working on it, it was the invocation and the quotations on the return string I was missing! Thanks for the help all
    – Tom S
    Commented May 15, 2020 at 1:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.