2

I am trying to take the population census tract and calculate the percentage of population by each census tract in the field (Populati_2). To do this I'm creating a new field with the total sum of the population (pop).

To get the percentage I'm usingthe following expression on arcgis [Populati_2] / [Pop] *100. It works fine in arcgis but when I'm using it to calculate field management or python it just doesn't work.

I'm not sure how to format the expression, I have tried every single combination and it's just not working.

Here's part of the script:

arcpy.AddField_management(r"Results\popjoin.dbf", "Pop", "LONG", "", "", "5")
arcpy.AddField_management(r"Results\popjoin.dbf", "Pop2", "DOUBLE", "", "", "5")
arcpy.CalculateField_management(r"Results\popjoin.dbf", "Pop", summed_total)
arcpy.CalculateField_management(r"Results\popjoin.dbf", "Pop2", '''Populati_2] / [Pop] *100''')

This one gives me errors, but the following does not give me any errors but I get a 0 in every row instead of the calculation.

expression = "!Populati_2! / !Pop! * 100"

arcpy.CalculateField_management(r"Results\popjoin.dbf", "Pop2", expression, "PYTHON_9.3")
2

As you can read in the commands, be careful what is a VBS and what a Python command/expression.

fc = "file_name"

# http://gis.stackexchange.com/a/82251/53268
summed_total = 0
with arcpy.da.SearchCursor(fc, "Populati_2") as cursor:
    for row in cursor:
        summed_total = summed_total + row[0]

arcpy.AddField_management(fc, "Pop", "LONG", "", "", "5")
arcpy.CalculateField_management(fc, "Pop", summed_total)

arcpy.AddField_management(fc, "Pop2", "DOUBLE", "", "", "5")
arcpy.CalculateField_management(fc, "Pop2", "!Populati_2! / !Pop! * 100", "PYTHON", "#")

If you have problems with the expression, you can always use the Field Calculate Toolbox to build your expression. See your old Result under Geoprocessing -> Results

arcgis result

With a double click on Calculate Field you can open the toolbox. Here you can use the expression builder (make sure you set Python as Parser):

calculate field

0

If you are unsure of the expression syntax, try the following:

  1. Crate a module in ModuleBuilder, add the Calculate Field tool, define all parameters, and run the model.
  2. If it runs successfully, export the model File>Export to python script
  3. Use the python expression syntax from the exported .py from step 2 into your python Calculate Field statement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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