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
Ad

More Related Content

Viewers also liked (14)

StephenJonesResume1November2015
StephenJonesResume1November2015StephenJonesResume1November2015
StephenJonesResume1November2015
Stephen Jones
 
Essay writing service
Essay writing serviceEssay writing service
Essay writing service
Shey1979
 
DESCRIPTION OF PRODUCTS & SERVICES
DESCRIPTION OF PRODUCTS & SERVICESDESCRIPTION OF PRODUCTS & SERVICES
DESCRIPTION OF PRODUCTS & SERVICES
Fitness Culture
 
revenue generator Sheet1
revenue generator Sheet1revenue generator Sheet1
revenue generator Sheet1
Fitness Culture
 
преступление и наказание
преступление и наказаниепреступление и наказание
преступление и наказание
SnezhanaP10
 
El continente americano
El continente americanoEl continente americano
El continente americano
Esthela Tejada
 
Влада золота в повісті Бальзака Гобсек
Влада золота в повісті Бальзака ГобсекВлада золота в повісті Бальзака Гобсек
Влада золота в повісті Бальзака Гобсек
SnezhanaP10
 
3 ključna problema svakodnevnog poslovanja! Pitali smo poduzetnike
3 ključna problema svakodnevnog poslovanja! Pitali smo poduzetnike3 ključna problema svakodnevnog poslovanja! Pitali smo poduzetnike
3 ključna problema svakodnevnog poslovanja! Pitali smo poduzetnike
Hrvatski Telekom
 
Limitedeunafuncion 140412082144-phpapp01
Limitedeunafuncion 140412082144-phpapp01Limitedeunafuncion 140412082144-phpapp01
Limitedeunafuncion 140412082144-phpapp01
yanirak
 
Guiding Principles for Experience Design
Guiding Principles for Experience DesignGuiding Principles for Experience Design
Guiding Principles for Experience Design
Ian Fitzpatrick
 
Guide line for groth and development
Guide line for groth and developmentGuide line for groth and development
Guide line for groth and development
DR.MANOJ KR VERMA
 
Report on sabah claim
Report on sabah claimReport on sabah claim
Report on sabah claim
Jewel Mercader
 
Historia Power Point
Historia Power Point Historia Power Point
Historia Power Point
yorman pizarro
 
StephenJonesResume1November2015
StephenJonesResume1November2015StephenJonesResume1November2015
StephenJonesResume1November2015
Stephen Jones
 
Essay writing service
Essay writing serviceEssay writing service
Essay writing service
Shey1979
 
DESCRIPTION OF PRODUCTS & SERVICES
DESCRIPTION OF PRODUCTS & SERVICESDESCRIPTION OF PRODUCTS & SERVICES
DESCRIPTION OF PRODUCTS & SERVICES
Fitness Culture
 
revenue generator Sheet1
revenue generator Sheet1revenue generator Sheet1
revenue generator Sheet1
Fitness Culture
 
преступление и наказание
преступление и наказаниепреступление и наказание
преступление и наказание
SnezhanaP10
 
El continente americano
El continente americanoEl continente americano
El continente americano
Esthela Tejada
 
Влада золота в повісті Бальзака Гобсек
Влада золота в повісті Бальзака ГобсекВлада золота в повісті Бальзака Гобсек
Влада золота в повісті Бальзака Гобсек
SnezhanaP10
 
3 ključna problema svakodnevnog poslovanja! Pitali smo poduzetnike
3 ključna problema svakodnevnog poslovanja! Pitali smo poduzetnike3 ključna problema svakodnevnog poslovanja! Pitali smo poduzetnike
3 ključna problema svakodnevnog poslovanja! Pitali smo poduzetnike
Hrvatski Telekom
 
Limitedeunafuncion 140412082144-phpapp01
Limitedeunafuncion 140412082144-phpapp01Limitedeunafuncion 140412082144-phpapp01
Limitedeunafuncion 140412082144-phpapp01
yanirak
 
Guiding Principles for Experience Design
Guiding Principles for Experience DesignGuiding Principles for Experience Design
Guiding Principles for Experience Design
Ian Fitzpatrick
 
Guide line for groth and development
Guide line for groth and developmentGuide line for groth and development
Guide line for groth and development
DR.MANOJ KR VERMA
 

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

Data Migrations in the App Engine Datastore
Data Migrations in the App Engine DatastoreData Migrations in the App Engine Datastore
Data Migrations in the App Engine Datastore
Ryan Morlok
 
Educational Objectives After successfully completing this assignmen.pdf
Educational Objectives After successfully completing this assignmen.pdfEducational Objectives After successfully completing this assignmen.pdf
Educational Objectives After successfully completing this assignmen.pdf
rajeshjangid1865
 
Wiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programmingWiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programming
AnalyticsConf
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
Connex
 
Lecture 24 multiple-fileprograming.pptx
Lecture 24 multiple-fileprograming.pptxLecture 24 multiple-fileprograming.pptx
Lecture 24 multiple-fileprograming.pptx
AyeCS11
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
Oon Arfiandwi
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Pa2 session 1
Pa2 session 1Pa2 session 1
Pa2 session 1
aiclub_slides
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
Sunny Shaikh
 
Unit testing presentation
Unit testing presentationUnit testing presentation
Unit testing presentation
Arthur Freyman
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
Adam Getchell
 
Property Based Testing in PHP
Property Based Testing in PHPProperty Based Testing in PHP
Property Based Testing in PHP
vinaikopp
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
Purvik Rana
 
Py.test
Py.testPy.test
Py.test
soasme
 
2014 International Software Testing Conference in Seoul
2014 International Software Testing Conference in Seoul2014 International Software Testing Conference in Seoul
2014 International Software Testing Conference in Seoul
Jongwook Woo
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
ShaownRoy1
 
Python Basic for Data science enthusiast
Python Basic for Data science enthusiastPython Basic for Data science enthusiast
Python Basic for Data science enthusiast
tomil53840
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
Ahmet Bulut
 
Modules of the twenties
Modules of the twentiesModules of the twenties
Modules of the twenties
Puppet
 
Data Migrations in the App Engine Datastore
Data Migrations in the App Engine DatastoreData Migrations in the App Engine Datastore
Data Migrations in the App Engine Datastore
Ryan Morlok
 
Educational Objectives After successfully completing this assignmen.pdf
Educational Objectives After successfully completing this assignmen.pdfEducational Objectives After successfully completing this assignmen.pdf
Educational Objectives After successfully completing this assignmen.pdf
rajeshjangid1865
 
Wiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programmingWiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programming
AnalyticsConf
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
Connex
 
Lecture 24 multiple-fileprograming.pptx
Lecture 24 multiple-fileprograming.pptxLecture 24 multiple-fileprograming.pptx
Lecture 24 multiple-fileprograming.pptx
AyeCS11
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
Oon Arfiandwi
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
Sunny Shaikh
 
Unit testing presentation
Unit testing presentationUnit testing presentation
Unit testing presentation
Arthur Freyman
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
Adam Getchell
 
Property Based Testing in PHP
Property Based Testing in PHPProperty Based Testing in PHP
Property Based Testing in PHP
vinaikopp
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
Purvik Rana
 
Py.test
Py.testPy.test
Py.test
soasme
 
2014 International Software Testing Conference in Seoul
2014 International Software Testing Conference in Seoul2014 International Software Testing Conference in Seoul
2014 International Software Testing Conference in Seoul
Jongwook Woo
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
ShaownRoy1
 
Python Basic for Data science enthusiast
Python Basic for Data science enthusiastPython Basic for Data science enthusiast
Python Basic for Data science enthusiast
tomil53840
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
Ahmet Bulut
 
Modules of the twenties
Modules of the twentiesModules of the twenties
Modules of the twenties
Puppet
 
Ad

More from DUSPviz (20)

Intro to inkscape
Intro to inkscapeIntro to inkscape
Intro to inkscape
DUSPviz
 
Intro to Tableau Public
Intro to Tableau PublicIntro to Tableau Public
Intro to Tableau Public
DUSPviz
 
Mapping with Adobe CC
Mapping with Adobe CCMapping with Adobe CC
Mapping with Adobe CC
DUSPviz
 
Intro to Microsoft Access
Intro to Microsoft AccessIntro to Microsoft Access
Intro to Microsoft Access
DUSPviz
 
Intro to Adobe Photoshop
Intro to Adobe PhotoshopIntro to Adobe Photoshop
Intro to Adobe Photoshop
DUSPviz
 
Intro to Adobe Illustrator
Intro to Adobe IllustratorIntro to Adobe Illustrator
Intro to Adobe Illustrator
DUSPviz
 
Intro to AutoCAD
Intro to AutoCADIntro to AutoCAD
Intro to AutoCAD
DUSPviz
 
Google Fusion Tables
Google Fusion TablesGoogle Fusion Tables
Google Fusion Tables
DUSPviz
 
Habits of Effective Designers - Handout
Habits of Effective Designers - HandoutHabits of Effective Designers - Handout
Habits of Effective Designers - Handout
DUSPviz
 
Habits of Effective Designers
Habits of Effective DesignersHabits of Effective Designers
Habits of Effective Designers
DUSPviz
 
Intro to Adobe Illustrator
Intro to Adobe IllustratorIntro to Adobe Illustrator
Intro to Adobe Illustrator
DUSPviz
 
Intro to Adobe Photoshop
Intro to Adobe PhotoshopIntro to Adobe Photoshop
Intro to Adobe Photoshop
DUSPviz
 
Introduction to InDesign
Introduction to InDesignIntroduction to InDesign
Introduction to InDesign
DUSPviz
 
The DUSP GIS Data Drive
The DUSP GIS Data DriveThe DUSP GIS Data Drive
The DUSP GIS Data Drive
DUSPviz
 
GIS Orientation 2015
GIS Orientation 2015GIS Orientation 2015
GIS Orientation 2015
DUSPviz
 
Setting up your DUSP ArcGIS Environment
Setting up your DUSP ArcGIS EnvironmentSetting up your DUSP ArcGIS Environment
Setting up your DUSP ArcGIS Environment
DUSPviz
 
AFS Connection Instructions
AFS Connection InstructionsAFS Connection Instructions
AFS Connection Instructions
DUSPviz
 
Intro to ArcGIS ModelBuilder
Intro to ArcGIS ModelBuilderIntro to ArcGIS ModelBuilder
Intro to ArcGIS ModelBuilder
DUSPviz
 
DUSPviz Rhino 3D Workshop
DUSPviz Rhino 3D WorkshopDUSPviz Rhino 3D Workshop
DUSPviz Rhino 3D Workshop
DUSPviz
 
Drawing for planners_ivanov
Drawing for planners_ivanovDrawing for planners_ivanov
Drawing for planners_ivanov
DUSPviz
 
Intro to inkscape
Intro to inkscapeIntro to inkscape
Intro to inkscape
DUSPviz
 
Intro to Tableau Public
Intro to Tableau PublicIntro to Tableau Public
Intro to Tableau Public
DUSPviz
 
Mapping with Adobe CC
Mapping with Adobe CCMapping with Adobe CC
Mapping with Adobe CC
DUSPviz
 
Intro to Microsoft Access
Intro to Microsoft AccessIntro to Microsoft Access
Intro to Microsoft Access
DUSPviz
 
Intro to Adobe Photoshop
Intro to Adobe PhotoshopIntro to Adobe Photoshop
Intro to Adobe Photoshop
DUSPviz
 
Intro to Adobe Illustrator
Intro to Adobe IllustratorIntro to Adobe Illustrator
Intro to Adobe Illustrator
DUSPviz
 
Intro to AutoCAD
Intro to AutoCADIntro to AutoCAD
Intro to AutoCAD
DUSPviz
 
Google Fusion Tables
Google Fusion TablesGoogle Fusion Tables
Google Fusion Tables
DUSPviz
 
Habits of Effective Designers - Handout
Habits of Effective Designers - HandoutHabits of Effective Designers - Handout
Habits of Effective Designers - Handout
DUSPviz
 
Habits of Effective Designers
Habits of Effective DesignersHabits of Effective Designers
Habits of Effective Designers
DUSPviz
 
Intro to Adobe Illustrator
Intro to Adobe IllustratorIntro to Adobe Illustrator
Intro to Adobe Illustrator
DUSPviz
 
Intro to Adobe Photoshop
Intro to Adobe PhotoshopIntro to Adobe Photoshop
Intro to Adobe Photoshop
DUSPviz
 
Introduction to InDesign
Introduction to InDesignIntroduction to InDesign
Introduction to InDesign
DUSPviz
 
The DUSP GIS Data Drive
The DUSP GIS Data DriveThe DUSP GIS Data Drive
The DUSP GIS Data Drive
DUSPviz
 
GIS Orientation 2015
GIS Orientation 2015GIS Orientation 2015
GIS Orientation 2015
DUSPviz
 
Setting up your DUSP ArcGIS Environment
Setting up your DUSP ArcGIS EnvironmentSetting up your DUSP ArcGIS Environment
Setting up your DUSP ArcGIS Environment
DUSPviz
 
AFS Connection Instructions
AFS Connection InstructionsAFS Connection Instructions
AFS Connection Instructions
DUSPviz
 
Intro to ArcGIS ModelBuilder
Intro to ArcGIS ModelBuilderIntro to ArcGIS ModelBuilder
Intro to ArcGIS ModelBuilder
DUSPviz
 
DUSPviz Rhino 3D Workshop
DUSPviz Rhino 3D WorkshopDUSPviz Rhino 3D Workshop
DUSPviz Rhino 3D Workshop
DUSPviz
 
Drawing for planners_ivanov
Drawing for planners_ivanovDrawing for planners_ivanov
Drawing for planners_ivanov
DUSPviz
 
Ad

Recently uploaded (20)

录取通知书加拿大TMU毕业证多伦多都会大学电子版毕业证成绩单
录取通知书加拿大TMU毕业证多伦多都会大学电子版毕业证成绩单录取通知书加拿大TMU毕业证多伦多都会大学电子版毕业证成绩单
录取通知书加拿大TMU毕业证多伦多都会大学电子版毕业证成绩单
Taqyea
 
Process Mining at Dimension Data - Jan vermeulen
Process Mining at Dimension Data - Jan vermeulenProcess Mining at Dimension Data - Jan vermeulen
Process Mining at Dimension Data - Jan vermeulen
Process mining Evangelist
 
RAG Chatbot using AWS Bedrock and Streamlit Framework
RAG Chatbot using AWS Bedrock and Streamlit FrameworkRAG Chatbot using AWS Bedrock and Streamlit Framework
RAG Chatbot using AWS Bedrock and Streamlit Framework
apanneer
 
Automation Platforms and Process Mining - success story
Automation Platforms and Process Mining - success storyAutomation Platforms and Process Mining - success story
Automation Platforms and Process Mining - success story
Process mining Evangelist
 
Deloitte - A Framework for Process Mining Projects
Deloitte - A Framework for Process Mining ProjectsDeloitte - A Framework for Process Mining Projects
Deloitte - A Framework for Process Mining Projects
Process mining Evangelist
 
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
muhammed84essa
 
Process Mining and Official Statistics - CBS
Process Mining and Official Statistics - CBSProcess Mining and Official Statistics - CBS
Process Mining and Official Statistics - CBS
Process mining Evangelist
 
Microsoft Excel: A Comprehensive Overview
Microsoft Excel: A Comprehensive OverviewMicrosoft Excel: A Comprehensive Overview
Microsoft Excel: A Comprehensive Overview
GinaTomarongRegencia
 
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
bastakwyry
 
AWS-AIML-PRESENTATION RELATED TO DATA SCIENCE TO DATA
AWS-AIML-PRESENTATION RELATED TO DATA SCIENCE TO DATAAWS-AIML-PRESENTATION RELATED TO DATA SCIENCE TO DATA
AWS-AIML-PRESENTATION RELATED TO DATA SCIENCE TO DATA
SnehaBoja
 
4. Multivariable statistics_Using Stata_2025.pdf
4. Multivariable statistics_Using Stata_2025.pdf4. Multivariable statistics_Using Stata_2025.pdf
4. Multivariable statistics_Using Stata_2025.pdf
axonneurologycenter1
 
E-Book-TOEFL-Masuk-PTN.pdf hahahahaahahahah
E-Book-TOEFL-Masuk-PTN.pdf hahahahaahahahahE-Book-TOEFL-Masuk-PTN.pdf hahahahaahahahah
E-Book-TOEFL-Masuk-PTN.pdf hahahahaahahahah
RyanRahardjo2
 
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
disnakertransjabarda
 
L1_Slides_Foundational Concepts_508.pptx
L1_Slides_Foundational Concepts_508.pptxL1_Slides_Foundational Concepts_508.pptx
L1_Slides_Foundational Concepts_508.pptx
38NoopurPatel
 
problem solving.presentation slideshow bsc nursing
problem solving.presentation slideshow bsc nursingproblem solving.presentation slideshow bsc nursing
problem solving.presentation slideshow bsc nursing
vishnudathas123
 
How to regulate and control your it-outsourcing provider with process mining
How to regulate and control your it-outsourcing provider with process miningHow to regulate and control your it-outsourcing provider with process mining
How to regulate and control your it-outsourcing provider with process mining
Process mining Evangelist
 
FPET_Implementation_2_MA to 360 Engage Direct.pptx
FPET_Implementation_2_MA to 360 Engage Direct.pptxFPET_Implementation_2_MA to 360 Engage Direct.pptx
FPET_Implementation_2_MA to 360 Engage Direct.pptx
ssuser4ef83d
 
50_questions_full.pptxdddddddddddddddddd
50_questions_full.pptxdddddddddddddddddd50_questions_full.pptxdddddddddddddddddd
50_questions_full.pptxdddddddddddddddddd
emir73065
 
717239550-Hotel-Management-Ppt-Final.pptx
717239550-Hotel-Management-Ppt-Final.pptx717239550-Hotel-Management-Ppt-Final.pptx
717239550-Hotel-Management-Ppt-Final.pptx
dharmendrasingh31102
 
Volkswagen - Analyzing the World's Biggest Purchasing Process
Volkswagen - Analyzing the World's Biggest Purchasing ProcessVolkswagen - Analyzing the World's Biggest Purchasing Process
Volkswagen - Analyzing the World's Biggest Purchasing Process
Process mining Evangelist
 
录取通知书加拿大TMU毕业证多伦多都会大学电子版毕业证成绩单
录取通知书加拿大TMU毕业证多伦多都会大学电子版毕业证成绩单录取通知书加拿大TMU毕业证多伦多都会大学电子版毕业证成绩单
录取通知书加拿大TMU毕业证多伦多都会大学电子版毕业证成绩单
Taqyea
 
Process Mining at Dimension Data - Jan vermeulen
Process Mining at Dimension Data - Jan vermeulenProcess Mining at Dimension Data - Jan vermeulen
Process Mining at Dimension Data - Jan vermeulen
Process mining Evangelist
 
RAG Chatbot using AWS Bedrock and Streamlit Framework
RAG Chatbot using AWS Bedrock and Streamlit FrameworkRAG Chatbot using AWS Bedrock and Streamlit Framework
RAG Chatbot using AWS Bedrock and Streamlit Framework
apanneer
 
Automation Platforms and Process Mining - success story
Automation Platforms and Process Mining - success storyAutomation Platforms and Process Mining - success story
Automation Platforms and Process Mining - success story
Process mining Evangelist
 
Deloitte - A Framework for Process Mining Projects
Deloitte - A Framework for Process Mining ProjectsDeloitte - A Framework for Process Mining Projects
Deloitte - A Framework for Process Mining Projects
Process mining Evangelist
 
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
muhammed84essa
 
Process Mining and Official Statistics - CBS
Process Mining and Official Statistics - CBSProcess Mining and Official Statistics - CBS
Process Mining and Official Statistics - CBS
Process mining Evangelist
 
Microsoft Excel: A Comprehensive Overview
Microsoft Excel: A Comprehensive OverviewMicrosoft Excel: A Comprehensive Overview
Microsoft Excel: A Comprehensive Overview
GinaTomarongRegencia
 
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
bastakwyry
 
AWS-AIML-PRESENTATION RELATED TO DATA SCIENCE TO DATA
AWS-AIML-PRESENTATION RELATED TO DATA SCIENCE TO DATAAWS-AIML-PRESENTATION RELATED TO DATA SCIENCE TO DATA
AWS-AIML-PRESENTATION RELATED TO DATA SCIENCE TO DATA
SnehaBoja
 
4. Multivariable statistics_Using Stata_2025.pdf
4. Multivariable statistics_Using Stata_2025.pdf4. Multivariable statistics_Using Stata_2025.pdf
4. Multivariable statistics_Using Stata_2025.pdf
axonneurologycenter1
 
E-Book-TOEFL-Masuk-PTN.pdf hahahahaahahahah
E-Book-TOEFL-Masuk-PTN.pdf hahahahaahahahahE-Book-TOEFL-Masuk-PTN.pdf hahahahaahahahah
E-Book-TOEFL-Masuk-PTN.pdf hahahahaahahahah
RyanRahardjo2
 
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
disnakertransjabarda
 
L1_Slides_Foundational Concepts_508.pptx
L1_Slides_Foundational Concepts_508.pptxL1_Slides_Foundational Concepts_508.pptx
L1_Slides_Foundational Concepts_508.pptx
38NoopurPatel
 
problem solving.presentation slideshow bsc nursing
problem solving.presentation slideshow bsc nursingproblem solving.presentation slideshow bsc nursing
problem solving.presentation slideshow bsc nursing
vishnudathas123
 
How to regulate and control your it-outsourcing provider with process mining
How to regulate and control your it-outsourcing provider with process miningHow to regulate and control your it-outsourcing provider with process mining
How to regulate and control your it-outsourcing provider with process mining
Process mining Evangelist
 
FPET_Implementation_2_MA to 360 Engage Direct.pptx
FPET_Implementation_2_MA to 360 Engage Direct.pptxFPET_Implementation_2_MA to 360 Engage Direct.pptx
FPET_Implementation_2_MA to 360 Engage Direct.pptx
ssuser4ef83d
 
50_questions_full.pptxdddddddddddddddddd
50_questions_full.pptxdddddddddddddddddd50_questions_full.pptxdddddddddddddddddd
50_questions_full.pptxdddddddddddddddddd
emir73065
 
717239550-Hotel-Management-Ppt-Final.pptx
717239550-Hotel-Management-Ppt-Final.pptx717239550-Hotel-Management-Ppt-Final.pptx
717239550-Hotel-Management-Ppt-Final.pptx
dharmendrasingh31102
 
Volkswagen - Analyzing the World's Biggest Purchasing Process
Volkswagen - Analyzing the World's Biggest Purchasing ProcessVolkswagen - Analyzing the World's Biggest Purchasing Process
Volkswagen - Analyzing the World's Biggest Purchasing Process
Process mining Evangelist
 

Python Programming for ArcGIS: Part II

  • 1. 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.
  • 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