Wednesday 29 June 2016

Use Python in ArcGIS Field Calculator to return value based on numeric value in any of three other fields


I am trying to calculate a new field in ArcGIS 10.5 Desktop using the field calculator, based on the value in any or all of three other fields in the same table. I have not used Python for a while, and am forgetting how to do this.



In essence, this should calculate if any of three types of a crop are being grown in an area. If at least one has an area greater than 1 hectare, then it should return "1" (if two or three types are present, it should give the same answer). The input fields and criteria:



  • Dry season rice > 1 hectare

  • Wet season rice > 1 hectare

  • Upland rice > 1 hectare

  • If any of these are true, then return "1" to new field I have already created, otherwise, new field is 0.


I have tried a few options in Python, but none have worked so far, e.g.:


def calc(Dry_area_1,Wet_area_1,Up_rice_1):
if Dry_Rice > 1:

Grow_Rice = 1
elif Wet_Rice > 1:
Grow_Rice = 1
elif Up_Rice > 1:
Grow_Rice = 1
else
return 0

Am I overlooking something very simple at a late hour of the night here?



Answer




You are confusing the way you define the function.


Your function needs to reference the variables(fields) called by the function.


Your function calls Dry_area_1, Wet_area_1, Up_rice_1, yet you don't reference any of those in the function.


You also need to return a value, not assign it to a variable. You're trying to assign Grow_Rice, but you need to return a value instead.


I think this is what you're going for:


def calc(Dry_area_1, Wet_area_1, Up_rice_1):
if Dry_area_1 > 1:
return 1
elif Wet_area_1 > 1:
return 1

elif Up_rice_1 > 1:
return 1
else:
return 0

then in the expression box:


calc(!Dry_area_1!, !Wet_area_1!, !Up_rice_1!)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...