Select to view content in your preferred language

ArcGIS Desktop Advanced 10.2 - Calculate Field with codeblock?

4678
2
Jump to solution
03-03-2015 10:06 AM
VincentLaunstorfer
Frequent Contributor

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

0 Kudos
1 Solution

Accepted Solutions
VincentLaunstorfer
Frequent Contributor

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)

View solution in original post

0 Kudos
2 Replies
DarrenWiens2
MVP Honored Contributor

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"""

0 Kudos
VincentLaunstorfer
Frequent Contributor

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)
0 Kudos