SlideShare a Scribd company logo
Python Programming for Arcgis 2
Daniel Sheehan
dsheehan@mit.edu, gishelp@mit.edu
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.
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
Slides available at …
• http://web.mit.edu/dsheehan/www/
dataForPythonIAP2015.zip (same data as
yesterday)
• http://web.mit.edu/dsheehan/www/
PythonProgrammingforArcgis2.pdf
Outline
• More data types
• Python functions
• Accessing Attribute Tables
• Select by attributes and location
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
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)
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]
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
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
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)
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
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
Exercise 1: Function to return shapefile
name
• Take in full file path string:
“C:Usersdsheehandesktopinterstatehigh
ways.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()
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
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
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:dsheehandesktopInterstateHighways.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.
Exercise 3
• Working with cursors
• Select by attributes
• Select by location
Exercise 3 - cursor
We are working with a shapefile, stepping
through the atttribute table of a FEATURE
CLASS with the cursor:
FC =
"C:UsersdsheehanDesktopkenyaDistrict2.shp
"
with arcpy.da.SearchCursor(FC, ("DISTRICT")) as cursor:
for row in cursor:
print row[0]
del cursor
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:Usersdsheehan
DesktopkenyaDistricts.shp", "lyr")
Inside loop
arcpy.SelectLayerByAttribute_management("lyr",
"NEW_SELECTION", ' "DISTRICT" = '' + row[0] + ''')
Confused by mix of quotes, single and double?
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
Exercise 3 - result
import arcpy, os
try:
with
arcpy.da.SearchCursor("C:UsersdsheehanDesktopPython2015currentkenyaDistricts.
shp", ("DISTRICT")) as cursor:
arcpy.MakeFeatureLayer_management("C:UsersdsheehanDesktopPython2015current
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
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

More Related Content

PDF
Python Programming for ArcGIS: Part I
PPTX
Programing for problem solving ( airline reservation system)
PPT
A intro to (hosted) Shiny Apps
PDF
CIRCUIT 2015 - Glimpse of perceptual diff
PDF
Building interactive web app with shiny
PPTX
2CPP13 - Operator Overloading
PDF
Building powerful dashboards with r shiny
PPTX
Type Casting C# - Lec4 (Workshop on C# Programming: Learn to Build)
Python Programming for ArcGIS: Part I
Programing for problem solving ( airline reservation system)
A intro to (hosted) Shiny Apps
CIRCUIT 2015 - Glimpse of perceptual diff
Building interactive web app with shiny
2CPP13 - Operator Overloading
Building powerful dashboards with r shiny
Type Casting C# - Lec4 (Workshop on C# Programming: Learn to Build)

Viewers also liked (14)

DOCX
StephenJonesResume1November2015
PPTX
Essay writing service
PDF
המלצה פניקס.יצחק בלייר
DOC
DESCRIPTION OF PRODUCTS & SERVICES
PDF
revenue generator Sheet1
PPT
преступление и наказание
PPTX
El continente americano
PPT
Влада золота в повісті Бальзака Гобсек
PDF
3 ključna problema svakodnevnog poslovanja! Pitali smo poduzetnike
PDF
Limitedeunafuncion 140412082144-phpapp01
PDF
Guiding Principles for Experience Design
PPTX
Guide line for groth and development
DOCX
Report on sabah claim
PPTX
Historia Power Point
StephenJonesResume1November2015
Essay writing service
המלצה פניקס.יצחק בלייר
DESCRIPTION OF PRODUCTS & SERVICES
revenue generator Sheet1
преступление и наказание
El continente americano
Влада золота в повісті Бальзака Гобсек
3 ključna problema svakodnevnog poslovanja! Pitali smo poduzetnike
Limitedeunafuncion 140412082144-phpapp01
Guiding Principles for Experience Design
Guide line for groth and development
Report on sabah claim
Historia Power Point
Ad

Similar to Python Programming for ArcGIS: Part II (20)

PPT
Python by ganesh kavhar
PPT
Python first day
PPT
Python first day
PPTX
Analytics with arcpy package detailing of Mapping Module Properties and Data ...
PPTX
Advanced geoprocessing with Python
PDF
Python Programming and GIS
PPTX
Python and GIS: Improving Your Workflow
PDF
Python gis
PPTX
Geoprocessing(Building Your Own Tool) and Geostatistical Analysis(An Introdu...
PPT
Python tutorial
PPT
Python tutorial
PPT
Arcgis training day_1
PPTX
Python language data types
PPTX
Python language data types
PPTX
Python language data types
PPTX
Python language data types
PPTX
Python language data types
PPTX
Python language data types
PPTX
Python language data types
PPT
Python programming tutorial for beginners
Python by ganesh kavhar
Python first day
Python first day
Analytics with arcpy package detailing of Mapping Module Properties and Data ...
Advanced geoprocessing with Python
Python Programming and GIS
Python and GIS: Improving Your Workflow
Python gis
Geoprocessing(Building Your Own Tool) and Geostatistical Analysis(An Introdu...
Python tutorial
Python tutorial
Arcgis training day_1
Python language data types
Python language data types
Python language data types
Python language data types
Python language data types
Python language data types
Python language data types
Python programming tutorial for beginners
Ad

More from DUSPviz (20)

PDF
Intro to inkscape
PDF
Intro to Tableau Public
PDF
Mapping with Adobe CC
PDF
Intro to Microsoft Access
PDF
Intro to Adobe Photoshop
PDF
Intro to Adobe Illustrator
PDF
Intro to AutoCAD
PDF
Google Fusion Tables
PDF
Habits of Effective Designers - Handout
PDF
Habits of Effective Designers
PDF
Intro to Adobe Illustrator
PDF
Intro to Adobe Photoshop
PDF
Introduction to InDesign
PDF
The DUSP GIS Data Drive
PDF
GIS Orientation 2015
PDF
Setting up your DUSP ArcGIS Environment
PDF
AFS Connection Instructions
PDF
Intro to ArcGIS ModelBuilder
PDF
DUSPviz Rhino 3D Workshop
PDF
Drawing for planners_ivanov
Intro to inkscape
Intro to Tableau Public
Mapping with Adobe CC
Intro to Microsoft Access
Intro to Adobe Photoshop
Intro to Adobe Illustrator
Intro to AutoCAD
Google Fusion Tables
Habits of Effective Designers - Handout
Habits of Effective Designers
Intro to Adobe Illustrator
Intro to Adobe Photoshop
Introduction to InDesign
The DUSP GIS Data Drive
GIS Orientation 2015
Setting up your DUSP ArcGIS Environment
AFS Connection Instructions
Intro to ArcGIS ModelBuilder
DUSPviz Rhino 3D Workshop
Drawing for planners_ivanov

Recently uploaded (20)

PDF
“Getting Started with Data Analytics Using R – Concepts, Tools & Case Studies”
PPTX
01_intro xxxxxxxxxxfffffffffffaaaaaaaaaaafg
PPTX
Microsoft-Fabric-Unifying-Analytics-for-the-Modern-Enterprise Solution.pptx
PPTX
Introduction to Firewall Analytics - Interfirewall and Transfirewall.pptx
PPTX
STUDY DESIGN details- Lt Col Maksud (21).pptx
PPTX
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
PDF
Galatica Smart Energy Infrastructure Startup Pitch Deck
PPTX
IB Computer Science - Internal Assessment.pptx
PPTX
Introduction to Knowledge Engineering Part 1
PPTX
Database Infoormation System (DBIS).pptx
PPTX
oil_refinery_comprehensive_20250804084928 (1).pptx
PDF
Fluorescence-microscope_Botany_detailed content
PPTX
Supervised vs unsupervised machine learning algorithms
PPTX
Business Ppt On Nestle.pptx huunnnhhgfvu
PDF
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
PDF
annual-report-2024-2025 original latest.
PPTX
Business Acumen Training GuidePresentation.pptx
PPTX
MODULE 8 - DISASTER risk PREPAREDNESS.pptx
PDF
Lecture1 pattern recognition............
“Getting Started with Data Analytics Using R – Concepts, Tools & Case Studies”
01_intro xxxxxxxxxxfffffffffffaaaaaaaaaaafg
Microsoft-Fabric-Unifying-Analytics-for-the-Modern-Enterprise Solution.pptx
Introduction to Firewall Analytics - Interfirewall and Transfirewall.pptx
STUDY DESIGN details- Lt Col Maksud (21).pptx
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
Galatica Smart Energy Infrastructure Startup Pitch Deck
IB Computer Science - Internal Assessment.pptx
Introduction to Knowledge Engineering Part 1
Database Infoormation System (DBIS).pptx
oil_refinery_comprehensive_20250804084928 (1).pptx
Fluorescence-microscope_Botany_detailed content
Supervised vs unsupervised machine learning algorithms
Business Ppt On Nestle.pptx huunnnhhgfvu
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
annual-report-2024-2025 original latest.
Business Acumen Training GuidePresentation.pptx
MODULE 8 - DISASTER risk PREPAREDNESS.pptx
Lecture1 pattern recognition............

Python Programming for ArcGIS: Part II

  • 1. Python Programming for Arcgis 2 Daniel Sheehan dsheehan@mit.edu, gishelp@mit.edu 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.
  • 2. 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
  • 3. Slides available at … • http://web.mit.edu/dsheehan/www/ dataForPythonIAP2015.zip (same data as yesterday) • http://web.mit.edu/dsheehan/www/ PythonProgrammingforArcgis2.pdf
  • 4. Outline • More data types • Python functions • Accessing Attribute Tables • Select by attributes and location
  • 5. 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
  • 6. 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)
  • 7. 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]
  • 8. 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
  • 9. 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
  • 10. 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)
  • 11. 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
  • 12. 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
  • 13. Exercise 1: Function to return shapefile name • Take in full file path string: “C:Usersdsheehandesktopinterstatehigh ways.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()
  • 14. 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
  • 15. 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
  • 16. 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:dsheehandesktopInterstateHighways.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.
  • 17. Exercise 3 • Working with cursors • Select by attributes • Select by location
  • 18. Exercise 3 - cursor We are working with a shapefile, stepping through the atttribute table of a FEATURE CLASS with the cursor: FC = "C:UsersdsheehanDesktopkenyaDistrict2.shp " with arcpy.da.SearchCursor(FC, ("DISTRICT")) as cursor: for row in cursor: print row[0] del cursor
  • 19. 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:Usersdsheehan DesktopkenyaDistricts.shp", "lyr") Inside loop arcpy.SelectLayerByAttribute_management("lyr", "NEW_SELECTION", ' "DISTRICT" = '' + row[0] + ''') Confused by mix of quotes, single and double?
  • 20. 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
  • 21. Exercise 3 - result import arcpy, os try: with arcpy.da.SearchCursor("C:UsersdsheehanDesktopPython2015currentkenyaDistricts. shp", ("DISTRICT")) as cursor: arcpy.MakeFeatureLayer_management("C:UsersdsheehanDesktopPython2015current 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
  • 22. 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