Monday, July 18, 2016

Exercise 4: Working with Fields & Selections

Goals and Objectives

The purpose of this exercise was to gain experience working with adding and calculating fields as well as using SQL statements within PyScripter. 


Methods 

This exercise carried out the exact same processes as those used in Exercise 1, only this time using Python instead of Model Builder.  While developing the script, comments were utilized to annotate each section of code.  The following steps were taken: 

  • importing system modules
  • importing Python modules: os, time, datetime
  • creating variables
  • processing data: adding fields, calculating fields, selecting features
  • debugging and running script


Results

The final script is displayed below. After successfully running this script, the results were viewed in ArcMap.

#-------------------------------------------------------------------
# Name:         Ex4
# Purpose:      Add field, calculate field, and apply SQL statement via Python
#
# Author:      williaan
#
# Created:     18/07/2016

#-------------------------------------------------------------------


#import system modules
import arcpy
from arcpy import env
import os
import time
import datetime
arcpy.env.overwriteOutput = True

#create variables
print "Creating Variables" ,datetime.datetime.now().strftime("%H:%M:%S")

#input variables
ex3geodatabasePath = "Q:\StudentCoursework\CHupy\GEOG.491.801.2167\WILLIAAN\Ex_3\Ex3_results.gdb"

#filename for 'dissolve output' fc name
intersectName = "IntersectedFcs"
dissolveOutput = os.path.join(ex3geodatabasePath,intersectName) + "_Dissolved"

#output variables
selectName = "DissolveFC_Selected"
finalSelect = os.path.join(ex3geodatabasePath,selectName)


#process: add field
print "Adding a field to the dissolved fcs" ,datetime.datetime.now().strftime("%H:%M:%S")
arcpy.AddField_management(dissolveOutput,"Area_km2", "FLOAT", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

#process: calculate field
print "Calculating the area in km2" ,datetime.datetime.now().strftime("%H:%M:%S")
arcpy.CalculateField_management(dissolveOutput, "Area_km2", "[Shape_Area] / 1000000", "VB", "")

#process: select areas greater than 2km
print "Selecting only polygons with areas greater than 2km" ,datetime.datetime.now().strftime("%H:%M:%S")
arcpy.Select_analysis(dissolveOutput, finalSelect, "Area_km2 > 2")

#process: add field
print "Adding a field for calculating compactness" ,datetime.datetime.now().strftime("%H:%M:%S")
arcpy.AddField_management(finalSelect, "Compactness_Float", "FLOAT", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

#process: calculate field
print "Calculating compactness" ,datetime.datetime.now().strftime("%H:%M:%S")
arcpy.CalculateField_management(finalSelect, "Compactness_Float", "[Shape_Area] / ([Shape_Length] * [Shape_Length])", "VB", "")

print "Calculations are complete." ,datetime.datetime.now().strftime("%H:%M:%S")



No comments:

Post a Comment