python programming for arcgis: part ii

22
Python Programming for Arcgis 2 Daniel Sheehan [email protected], [email protected] 9:30AM-12:30PM January 15, 2015 This class was originally developed by David Quinn and taught by David and Daniel in IAP 2010 and 2011.

Upload: duspviz

Post on 22-Feb-2017

254 views

Category:

Data & Analytics


1 download

TRANSCRIPT

Page 1: Python Programming for ArcGIS: Part II

Python Programming for Arcgis 2

Daniel Sheehan [email protected], [email protected]

9:30AM-12:30PM January 15, 2015

This class was originally developed by David Quinn and taught by David and Daniel in IAP

2010 and 2011.

Page 2: Python Programming for ArcGIS: Part II

Goals for the workshop (from yesterday)

• Learning enough Python to

– Access Arcgis commands through Python

– Access individual records from attribute table

– Acccess individual geometries for use in geoprocessing

• Develop the ability to record and document your geoprocessing

Page 3: Python Programming for ArcGIS: Part II

Slides available at …

• http://web.mit.edu/dsheehan/www/ dataForPythonIAP2015.zip (same data as yesterday)

• http://web.mit.edu/dsheehan/www/ PythonProgrammingforArcgis2.pdf

Page 4: Python Programming for ArcGIS: Part II

Outline

• More data types

• Python functions

• Accessing Attribute Tables

• Select by attributes and location

Page 5: Python Programming for ArcGIS: Part II

Lists = []

An ordered set of elements enclosed in square brackets.

Zero based (first element is accessed by typing list[0]).

# This is a list []

animals = [ 'dog ' , ' cat ' , 'horse ' , ' seal ' ]

print animals[3]

animals.append(‘owl’)

Lists are mutable

Page 6: Python Programming for ArcGIS: Part II

Tuples = ()

Zero base (first element of a non-empty tuple is

always tuple(0)

# This is a tuple

Countries = (‘Costa Rica’, ‘India’, ‘Abu Dhabi’)

# You cannot change a tuple (immutable)

Page 7: Python Programming for ArcGIS: Part II

String processing – slicing a string

# slicing a string

Name = ‘Massachusetts’

#Fenceposts – starting at index 1 and ending

# before index 2

Name[1:2]

# find the first 4 characters of Name

Name[:4]

Page 8: Python Programming for ArcGIS: Part II

Example: using length

len(Name) shows length of string

• Find the length of a string variable called name with a value of ‘Massachusetts’

• Print the last 4 characters in the name string

Page 9: Python Programming for ArcGIS: Part II

Example Function 1

# Python uses dynamic typing (type is set when

a variable is assigned or argument is passed)

# Save in file called test.py

def print_value(argument):

# Print the passed argument

print argument

# default return is none for a function

Page 10: Python Programming for ArcGIS: Part II

Import ‘test.py’ - DIY

# Importing a script(that is stored in the same folder, otherwise use full path)

import test

# print number from function

Answer = test.print_value(15)

Page 11: Python Programming for ArcGIS: Part II

Example Function 2

# Function will give an error if argument is not a number

# Save this file as example.py

def change_value(number):

# Add documentation here

number += 8

return number

Page 12: Python Programming for ArcGIS: Part II

Import ‘example.py’ - DIY

# Importing a script (that is stored in the same folder, otherwise use full path)

import example

# get new number from function

Answer = example.change_value(15)

print Answer

Page 13: Python Programming for ArcGIS: Part II

Exercise 1: Function to return shapefile name

• Take in full file path string:

“C:\\Users\\dsheehan\\desktop\\interstatehighways.shp”

• Return shapefile name:

“InterstateHighways.shp”

Should work for any full file path string, not one case. You should have a second .py file to call the function.

Examine python documentation http://doc.python.org; in particular string.split(), len()

Page 14: Python Programming for ArcGIS: Part II

Warning: beware when copying from slides

• Double quotes aren’t the same in PP as in IDLE

• Maintain indents so logic of the program remains as intended

• And don’t open shapefiles with a cursor that are open in Arcmap

Page 15: Python Programming for ArcGIS: Part II

Accessing the Attribute Table def sumUpLength(shapefile): # returns the length of all line segments in an attribute table import arcpy, os sumLength = 0.0 try: with arcpy.da.SearchCursor(shapefile, (“LENGTH”)) as cursor: for row in cursor: sumLength += row[0] del cursor except: return -9999 return sumLength

Page 16: Python Programming for ArcGIS: Part II

Exercise 2 Call the function in the previous slide (called

accessAT.py) from a .py file. You should submit

a full path to the shapefile

(example - “C:\\dsheehan\\desktop\\InterstateHighways.shp”)

as the argument to the function. Once this works,

add a where clause to the searchCursor function

to find only records with a length of 40 KM or

greater. Search help for Search Cursor and look for

AddFieldDelimiters.

Page 17: Python Programming for ArcGIS: Part II

Exercise 3

• Working with cursors

• Select by attributes

• Select by location

Page 18: Python Programming for ArcGIS: Part II

Exercise 3 - cursor

We are working with a shapefile, stepping through the atttribute table of a FEATURE CLASS with the cursor:

FC =

"C:\\Users\\dsheehan\\Desktop\\kenyaDistrict2.shp"

with arcpy.da.SearchCursor(FC, ("DISTRICT")) as cursor:

for row in cursor:

print row[0]

del cursor

Page 19: Python Programming for ArcGIS: Part II

Exercise 3 – selecting using attributes

Selecting by layer requires converting from a FEATURE CLASS to LAYER but uses the same shapefile but opened a second time. before loop arcpy.MakeFeatureLayer_management("C:\\Users\\dsheehan\\Desktop\\kenyaDistricts.shp", "lyr") Inside loop arcpy.SelectLayerByAttribute_management("lyr", "NEW_SELECTION", ' "DISTRICT" = \'' + row[0] + '\'') Confused by mix of quotes, single and double?

Page 20: Python Programming for ArcGIS: Part II

Exercise 3 – select by location

Using the Layer, not the feature class, all inside the loop:

arcpy.SelectLayerByLocation_management ("lyr", "BOUNDARY_TOUCHES", "lyr")

And checking the number selected:

theCount = arcpy.GetCount_management("lyr")

print theCount

Page 21: Python Programming for ArcGIS: Part II

Exercise 3 - result import arcpy, os try: with

arcpy.da.SearchCursor("C:\\Users\\dsheehan\\Desktop\\Python2015current\\kenyaDistricts.shp", ("DISTRICT")) as cursor:

arcpy.MakeFeatureLayer_management("C:\\Users\\dsheehan\\Desktop\\Python2015current\\kenyaDistricts2.shp", "lyr")

for row in cursor: arcpy.SelectLayerByAttribute_management("lyr", "NEW_SELECTION", ' "DISTRICT" = \'' +

row[0] + '\'') arcpy.SelectLayerByLocation_management ("lyr", "BOUNDARY_TOUCHES", "lyr") theCount = arcpy.GetCount_management("lyr") print row[0] print theCount arcpy.SelectLayerByLocation_management ("lyr", "BOUNDARY_TOUCHES", "lyr") theCount = arcpy.GetCount_management("lyr") print theCount del cursor except: print arcpy.GetMessages() raise

Page 22: Python Programming for ArcGIS: Part II

Try this at home:

• Add code to test whether any of the nearby polygons contain a specified district

• If not, select additional neighbors and test

• Count how many iterations before you find the specified district

• You should do this inside a while loop