By Charlie Frye, Esri Chief Cartographer
I do most of my data automation in Python–I’m no expert with Python, but I learned the basics a few years ago and that’s served me well. One of the tasks I frequently use Python for is automating the management of attributes, i.e., adding, deleting, and calculating fields. I learned VB prior to Python, so I had always used VBScript as my basis for field calculations. Recently, I learned that doing field calculations in Python scripts was not as stable as using Python code as the basis for my calculate statements. The issue, for me, was having my code not run, generating a bogus generic error. The development team figured it out and they’re working on fixing it for the 9.4 release.
In the meantime, it became obvious that I needed to learn how to use Python in my field calculations and there was nothing I could find in the online help to guide me in terms of proper syntax. I got some help from our geoprocessing team and here are three examples that might help you:
- Calculate one field’s value from another field. The trick here was to put exclamation points around the field name (versus brackets, single or double quotes, or any escape characters).
- Calculate a field value from a Python variable. After the above example, this one was deceptively easy. In this case, “tile” is an integer variable that I set in my Python script. No special characters needed, just make sure your Python variable is the right type (str(), etc. may be useful functions for converting variables).
- Last, here’s one that uses an advanced calculate statement. This is the statement I got help on (can you see why?!). Basically, I am calculating the Idx20_YN field based on ElevFld Mod 20. In Python the Mod function is accomplished with the % character. You can also see that the Python indentation scheme is also captured here:
gp.CalculateField_management(OutSimpConts,”Idx20_YN”, “k(!” + ElevFld + “!)”, “PYTHON”, “def k(elev):rn if elev % 20 == 0:rn return 0rn else:rn return 1″)