Hi,
In ArcGIS Advanced for Desktop 10.2, I am trying to calculate a field "ELEV_METER" in a shapefile with an expression and code-block as here:
expression = "getElev(double(!ELEV!))" codeblock = """def getElev(elev): if elev <> 0: return !ELEV!""" arcpy.CalculateField_management(fc, "ELEV_METER", expression, "PYTHON_9.3",codeblock)
trying to apply ressources from ESRI:
http://resources.arcgis.com/en/help/main/10.1/index.html#//00170000004m000000
The calculate field should be done only if the field ELEV is not 0, then the if statment...
But is does not work! Any guess?
Cheers
Solved! Go to Solution.
Thanks Daren,
In the codeblock, I now reference to the varaible elev in the return statment instead of the !ELEV! field directly. It is smarter.
However, what make the script crashing is the the CalculateField_management do not accept Null values for shapefile! Null values are possible only in Geodatabase, apparently.
It means, when elev = 0, CalculateField_management could not write Null in the "ELEV_METER" field...
Now it works as below:
expression = "getElev(!ELEV!)" codeblock = """def getElev(elev): if elev <> 0: return elev else: return -99""" arcpy.CalculateField_management(fc, "ELEV_METER", expression, "PYTHON_9.3", codeblock)
It generally helps narrow down the problem by including the error message, but in this case, I think the problem is in referencing the elevation field (!ELEV!) rather than the variable containing the current value of the elevation field (elev) within the codeblock. Try changing return !ELEV!""" to return elev"""
Thanks Daren,
In the codeblock, I now reference to the varaible elev in the return statment instead of the !ELEV! field directly. It is smarter.
However, what make the script crashing is the the CalculateField_management do not accept Null values for shapefile! Null values are possible only in Geodatabase, apparently.
It means, when elev = 0, CalculateField_management could not write Null in the "ELEV_METER" field...
Now it works as below:
expression = "getElev(!ELEV!)" codeblock = """def getElev(elev): if elev <> 0: return elev else: return -99""" arcpy.CalculateField_management(fc, "ELEV_METER", expression, "PYTHON_9.3", codeblock)