ArcPy and ArcGIS – Geospatial Analysis with Python... How does the computer know where the interpreter is?Make Python scripts executable when clicked on Adding the CSV module to the scri
Trang 3ArcPy and ArcGIS – Geospatial Analysis with Python
Trang 4ArcPy and ArcGIS – Geospatial Analysis with PythonCredits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and moreWhy subscribe?
Trang 5The XLRD and XLWT modules
Commonly used built-in functions
Commonly used standard library modulesSummary
2 Configuring the Python Environment
What is a Python script?
How Python executes a script
What is the Python interpreter?
Trang 6Which Python interpreter should be used?
How does the computer know where the interpreter is?Make Python scripts executable when clicked on
Adding the CSV module to the script
Trang 7The final script
Summary
4 Complex ArcPy Scripts and Generalizing FunctionsPython functions–Avoid repeating code
Trang 8Labelling and defining parameters
Adding data types
Adding the Bus Stop feature class as a parameterAdding the Census Block feature class as a parameterAdding the Census Block field as a parameter
Adding the output spreadsheet as a parameter
Adding the spreadsheet field names as a parameterAdding the SQL Statement as a parameter
Trang 9Generating a buffer from the bus stops feature class
Intersecting the bus stop buffer and census blocks
Populating the selected bus stop and buffer feature classesUpdating the text elements
Trang 12ArcPy and ArcGIS – Geospatial Analysis with Python
Trang 14ArcPy and ArcGIS – Geospatial Analysis with Python
Copyright © 2015 Packt Publishing
All rights reserved No part of this book may be reproduced, stored in a retrieval system,
or transmitted in any form or by any means, without the prior written permission of thepublisher, except in the case of brief quotations embedded in critical articles or reviews.Every effort has been made in the preparation of this book to ensure the accuracy of theinformation presented However, the information contained in this book is sold withoutwarranty, either express or implied Neither the author, nor Packt Publishing, and its
dealers and distributors will be held liable for any damages caused or alleged to be causeddirectly or indirectly by this book
Trang 19Silas Toms is a geospatial programmer and analyst with a love of geography, history,
food, and sports He resides in the San Francisco Bay Area and can’t decide which side ofthe Bay is more beautiful He received a bachelor’s degree in Geography from HumboldtState University and is currently pursuing a master’s degree in GIS at San Francisco StateUniversity With a background in GIS analysis for city governments and environmentalconsulting, Silas loves the combination of GIS and Python for analysis automation anddata manipulation
Working for Arini Geographics, Silas is helping governments understand how GIS canorganize and simplify the management of infrastructure and the environment This dualrole as a programmer and analyst allows him to use Python and GIS to quickly producegeospatial data and tools Combined with web mapping, these tools are transforming howgovernments work to serve the public He also teaches workshops on ArcPy and webmapping at the City College of San Francisco, while hoping to one day finish his master’sthesis
Silas has worked as a reviewer on the book Python Geospatial Analysis, Packt Publishing and is working on the book Python Geospatial Development, Packt Publishing to be
published in 2015
I would like to thank my girlfriend, Christine, for her encouragement and patience I
would like to thank my boss, Gabriel Paun, for his inspiration and for pushing me to
become a true GIS professional I would like to thank the faculty at HSU and SFSU fortheir help along the way, and I would like to thank my family for their belief in me and fornever asking me if I was going to become a teacher with my geography degree (eventhough I have and I love it!)
Trang 21Alessio Di Lorenzo is a marine biologist and has an MSc in Geographical Information
Systems (GIS) and Remote Sensing Since 2006, he has been dealing with the analysis anddevelopment of GIS applications dedicated to the study and spread of environmental andepidemiological data He is experienced in the use of the main proprietary and open sourceGIS software and programming languages
Dara O’Beirne is a certified GIS Professional (GISP) with over eight years of GIS and
Python experience Dara earned both his Bachelors and Masters of Arts degrees in
geography from San Francisco State University Dara is currently a GIS Analyst working
at Arini Geographics in Santa Clara, CA Before joining Arini Geographics, Dara was aGIS Analyst and technical lead at Towill Inc., a GIS and Land Surveying company inNorthern California At Towill, Dara played a central role in developing and implementingprocedures related to the collection and analysis of LiDAR data for environmental andengineering applications Prior to Towill, Dara gained his professional GIS experienceworking for the Golden Gate National Recreation Area managed by the National ParkService, one of the largest urban park systems in the world, which includes National
treasures, such as Alcatraz, Muir Woods, and the Marin Headlands His Master’s Thesisexamined the errors associated with measuring tree heights in an urban environment withboth traditional field methods and airborne LiDAR data
I would like to thank my wife, Kate, and daughter, Anya O’Beirne, for their patience andassistance during the review of this book
Marjorie Roswell is a web developer and map maker from Baltimore, MD She
purchased her first GIS in 1991, and built an application to assist citizen callers to theBaltimore Office of Recycling Recent projects include interactive maps of legislativescores, political endorsements, committees, election data, and advocacy interests
Her site http://committeemaps.org/ details Congressional committee membership, whilethe site http://farmbillprimer.org/ is devoted to mapping and charting federal food andfarm policy
Marjorie is the author of Drupal 5 Views Recipes, Packt Publishing She was the technical reviewer of jQuery UI 1.10, The User Interface Library for jQuery, Packt Publishing.
Mark Pazolli is an engineer and data scientist who uses ArcGIS and Python to help his
employers decipher the mountains of data they keep on the assets of the Western
Australian electrical network He has qualifications in Electrical Engineering, ComputerScience, and Applied Mathematics He appreciates excellent design and enjoys buildinginteresting things
Trang 23www.PacktPub.com
Trang 24Support files, eBooks, discount offers, and more
For support files and downloads related to your book, please visit www.PacktPub.com.Did you know that Packt offers eBook versions of every book published, with PDF andePub files available? You can upgrade to the eBook version at www.PacktPub.com and as
a print book customer, you are entitled to a discount on the eBook copy Get in touch with
us at < service@packtpub.com > for more details
At www.PacktPub.com, you can also read a collection of free technical articles, sign upfor a range of free newsletters and receive exclusive discounts and offers on Packt booksand eBooks
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt’s online digitalbook library Here, you can search, access, and read Packt’s entire library of books
Trang 25Fully searchable across every book published by PacktCopy and paste, print, and bookmark content
On demand and accessible via a web browser
Trang 26If you have an account with Packt at www.PacktPub.com, you can use this to accessPacktLib today and view 9 entirely free books Simply use your login credentials forimmediate access
Trang 28ArcGIS, the GIS software from industry leader ESRI, allows for the analysis and
presentation of geospatial data
The integration of Python into ArcGIS has made the ArcPy module an important tool forGIS students and professionals The ArcPy module provides a powerful way to improveproductivity when performing geospatial analysis From basic Python scripting throughadvanced ArcPy methods and properties, ArcPy and other Python modules will improvethe speed and repeatability of any GIS work flow
This book will guide you from basic Python scripting to advanced scripting tools Itfocuses on geospatial analysis scripting and touches on automating cartographic output
By the end of this book, you will be able to create reusable modules, add repeatableanalyses as script tools in ArcToolbox, and export maps automatically By reducing thetime-consuming nature of GIS from days to hours, one GIS professional can become aspowerful as a whole team
Trang 29Chapter 1, Introduction to Python for ArcGIS, offers a quick introduction to the basics ofPython, including other uses for the programming language It covers Python data typesand important modules used throughout the book
Chapter 2, Configuring the Python Environment, is an introduction to how Python works:its folder structure, executables, and modules It also explains importing modules intoscripts, the built-in modules, and covers Integrated Development Environments (IDEs),which are powerful programming aids
Chapter 3, Creating the First Python Script, demonstrates how to use ArcGIS
ModelBuilder to model the first analysis and then export it as a Python script Stringmanipulations and how to use file paths in Python are also introduced
Chapter 4, Complex ArcPy Scripts and Generalizing Functions, examines how to performanalyses and produce outputs that are not possible using ModelBuilder By using
functions, or reusable code blocks, repeating code is avoided
Chapter 5, ArcPy Cursors – Search, Insert, and Update, covers ArcPy data access cursorsand how they are used to search, update, or insert records in feature classes and tables Itexplains the quirks of iterating using cursors, and how to only select or update the records
of interest
Chapter 6, Working with ArcPy Geometry Objects, explores ArcPy Geometry objects andhow they are combined with cursors to perform spatial analysis It demonstrates how tobuffer, clip, reproject, and more using the data cursors and the Arcpy geometry typeswithout using ArcToolbox
Chapter 7, Creating a Script Tool, explains how to make scripts into tools that appear inArcToolbox and are dynamic in nature It explains how the tools and scripts communicateand how to set up the ArcTool dialog to correctly pass parameters to the script
Chapter 8, Introduction to ArcPy.Mapping, explores the powerful Arcpy.Mapping moduleand how to fix broken layer links, turn layers on and off, and dynamically adjust titles andtext It shows how to create dynamic map output based on a geospatial analysis
Chapter 9, More ArcPy.Mapping Techniques, introduces Layer objects, and their methodsand properties It demonstrates how to control map scales and extents for data frames, andcovers automated map export
Chapter 10, Advanced Geometry Object Methods, expands on the ArcPy Geometry objectmethods and properties It also explains how to create a module to save code for reuse insubsequent scripts, and demonstrates how to create Excel spreadsheets containing resultsfrom a geospatial analysis
Chapter 11, Network Analyst and Spatial Analyst with ArcPy, introduces the basics ofusing ArcPy for advanced geospatial analysis using the ArcGIS for Desktop NetworkAnalyst and Spatial Analyst Extensions
Trang 30understood to have a full grasp of ArcPy These topics include the Environment Settings,
XY values and Z and M resolutions, Spatial Reference Systems (Projections), the Describefunctions, and more
Trang 32You will need the proprietary or free version of ArcGIS 10.1/10.2/10.3 To support yourenvironment, you will need 2GB RAM, 32-bit or 64 bit machine hardware configuration,and Windows 7/8 Python 2.7 is required to do the programming and is installed alongwith ArcGIS
Trang 34This book is intended for GIS students and professionals who need an understanding ofhow to use ArcPy to reduce repetitive tasks and perform analysis faster It is also avaluable book for Python programmers who would like to understand how to automategeospatial analysis using the industry standard ArcGIS software and its ArcPy module
Trang 36In this book, you will find a number of styles of text that distinguish between differentkinds of information Here are some examples of these styles, and an explanation of theirmeaning
Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows: “The twodata pieces, the BusStopID and the averatePop variable are then added to a list.”
Trang 38Feedback from our readers is always welcome Let us know what you think about thisbook—what you liked or may have disliked Reader feedback is important for us todevelop titles that you really get the most out of
To send us general feedback, simply send an e-mail to < feedback@packtpub.com >, andmention the book title via the subject of your message
If there is a topic that you have expertise in and you are interested in either writing orcontributing to a book, see our author guide on www.packtpub.com/authors
Trang 40Now that you are the proud owner of a Packt book, we have a number of things to helpyou to get the most from your purchase
Trang 41You can download the example code files for all Packt books you have purchased fromyour account at http://www.packtpub.com If you purchased this book elsewhere, you canvisit http://www.packtpub.com/support and register to have the files e-mailed directly toyou
Trang 42We also provide you with a PDF file that has color images of the screenshots/diagramsused in this book The color images will help you better understand the changes in theoutput You can download this file from
http://www.packtpub.com/sites/default/files/downloads/8662OS_ColorImages.pdf
Trang 43Although we have taken every care to ensure the accuracy of our content, mistakes dohappen If you find a mistake in one of our books—maybe a mistake in the text or thecode—we would be grateful if you could report this to us By doing so, you can save otherreaders from frustration and help us improve subsequent versions of this book If you findany errata, please report them by visiting http://www.packtpub.com/submit-errata,
selecting your book, clicking on the Errata Submission Form link, and entering the
details of your errata Once your errata are verified, your submission will be accepted andthe errata will be uploaded to our website or added to any list of existing errata under theErrata section of that title
To view the previously submitted errata, go to
https://www.packtpub.com/books/content/support and enter the name of the book in the
search field The required information will appear under the Errata section.
Trang 44Piracy of copyright material on the Internet is an ongoing problem across all media AtPackt, we take the protection of our copyright and licenses very seriously If you comeacross any illegal copies of our works, in any form, on the Internet, please provide us withthe location address or website name immediately so that we can pursue a remedy
Please contact us at < copyright@packtpub.com > with a link to the suspected pirated
material
We appreciate your help in protecting our authors, and our ability to bring you valuablecontent