Python Basics II GIS Applications Spring 2017 1
Python Basics II GIS Applications Spring 2017 1
Python - Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). Lists in Python can contain items of different data types. misc. List= ["cake", 345, 10. 12, "ice cream", 70123437] record=[783469, "Jane", "Smith", 34, "125 Main St"] Lists are sequences like text strings. They are indexed, and start at index 0. 2
Python - Creating Lists A numbered list can be created with the range function which can include start and stop values and an increment. >>> listnew=range(5) >>> listnew [0, 1, 2, 3, 4] listnew=range(10, 2, -2) >>> listnew [10, 8, 6, 4] An empty list can be initialized with the slice operator [] lista=[] 3
Python - Operations on Lists Slice Operations >>> misc. List= ["cake", 345, 10. 12, "ice cream", 70123437] >>> misc. List[1] 345 >>> misc. List[2: 3] [10. 12] >>> misc. List[1: ] #includes from index 1 forward [345, 10. 12, 'ice cream', 70123437] >>> misc. List[: 3] # includes up to index 3 ['cake', 345, 10. 12] 4
Python - Operations on Lists unlike strings can be changed An item in a list can be updated with the slice operator, by using it on the left-hand side of the assignment operator. >>>>food. List=["apples", "beet", "carrots", "potatoes", "spinach", "zucchini"] >>> food. List[3]="oranges“ >>> food. List ['apples', 'beet', 'carrots', 'oranges', 'spinach', 'zucchini'] 5
Python - Operations on Lists Functions for finding the length of a list and for finding its largest and smallest elements. >>> misc. List= ["cake", 345, 10. 12, "ice cream", 70123437] >>> len(misc. List) 5 >>> min(misc. List) 10. 12 >>> max(misc. List) 'ice cream' 6
Python - Operations on Lists List concatenation uses + list 2=misc. List+food. List >>> list 2 ['cake', 345, 10. 12, 'ice cream', 70123437, 'apples', 'beet', 'carrots', 'oranges', 'spinach', 'zucchini'] Lists can be replicated using * n >>> list 3=[1, 2, 3] >>> list 3*3 [1, 2, 3, 1, 2, 3] 7
Python - Operations on Lists Checking for membership in a list using in or not in >>>>food. List=["apples", "beet", "carrots", "potatoes", "spinach", "zucchini"] >>> "apples" in food. List True >>> “squash" not in food. List True 8
Python - List Methods An empty list can be initialized with [] and then the append method can be used to append data to the end of the list: >>> a =[] >>> a. append("test") >>> a ['test'] >>> a. append("two") >>> a ['test', 'two'] 9
Python - List Methods list. count Returns count of how many times obj occurs in list 3=[1, 2, 3] >>> list 3*3 [1, 2, 3, 1, 2, 3] >>> list 4=list 3*3 >>> list 4. count(2) 3 10
Python - List Methods list. extend (seq) The method does not return a value but appends the contents of seq to an existing list. >>> alist=[1, 2, 3] >>> alist. extend([4, 5, 6]) >>> alist [1, 2, 3, 4, 5, 6] Difference between extend append >>> blist=[4, 5, 6] >>> blist. extend([7, 8, 9]) >>> blist [4, 5, 6, 7, 8, 9] >>> blist. append([7, 8, 9]) >>> blist [4, 5, 6, [7, 8, 9]] 11
Python - List Methods list. insert (index, obj) Inserts object obj into list at index >>> food. List ['apples', 'beet', 'carrots', 'oranges', 'spinach', 'zucchini'] >> food. List. insert(4, "potatoes") >>> food. List ['apples', 'beet', 'carrots', 'oranges', 'potatoes', 'spinach', 'zucchini'] 12
Python - List Methods List. remove (obj): This method does not return a value but removes the obj from the list. >>> food. List ['apples', 'beet', 'carrots', 'oranges', 'potatoes', 'spinach', 'zucchini'] >>> food. List. remove("beet") >>> food. List ['apples', 'carrots', 'oranges', 'potatoes', 'spinach', 'zucchini'] del – delates an element from a list given an index value del food. List[0] >>> food. List ['carrots', 'oranges', 'potatoes', 'spinach', 'zucchini'] 13
Python - List Methods list. index(obj)- returns the index of obj otherwise raises an exception indicating that obj was not found – returns only the index of the first occurrence >>> food. List ['carrots', 'oranges', 'potatoes', 'spinach', 'zucchini'] >>> food. List. index("potatoes") 2 14
Python - Lists Multi-dimensional (nested) lists: Multi-dimensional lists are lists of lists: a=[[0, 1, 2], [3, 4, 5]], [[6, 7, 8]] print a[1] [3, 4, 5] list 1= [2, 3] list 2= [4, 5] list 3=[list 1, list 2] list 3[0] 15
Python Lists versus Dictionaries To access an element of a list or an array, you simply refer to the number corresponding to its position in the sequence. The elements of dictionaries are accessed by “keys”, 16
Python Dictionaries A dictionary is a set of key: value pairs. All keys must be unique. Each key is separated from its value by a colon (: ), the items are separated by commas, all enclosed in curly braces creation: empty. Dict = {} thisdict={'a': 1, 'b': 23, 'c': "eggs"} >>> thisdict {'a': 1, 'c': 'eggs', 'b': 23} thisdict['a'] 1 deleting: del thisdict['b'] >>> thisdict {'a': 1, 'c': 'eggs'} 17
Python Dictionaries thisdict={'a': 1, 'b': 23, 'c': "eggs"} methods: thisdict. has_key('e') thisdict. keys() ‘c’ in thisdict. items() returns False returns [‘a’, ‘b’, ‘c’] returns True returns [(‘a’, 1), (‘c’, ‘eggs’), (‘b’, 23)] 18
Python - For Loops The for loop iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence for var in range(start [, stop [, inc]]): statements var can be any variable. The range statement can take start and stop values, and an increment. for food in food. List: print food apples beet carrots potatoes spinach zucchini a = ['Mary', 'had', 'a', 'little', 'lamb'] for i in range (len(a)): print i, a[i] 0 Mary 1 had 2 a 3 little 4 lamb 19
Python - While Loops while expr: statements a, b = 0, 1 while b < 100: print b a, b = b, a+b The while loop executes as long as the condition (here: b < 100) remains true. In Python any nonzero integer value is true; zero or null is false. The test used in the example is a simple comparison. 20
Python - While versus For Loops x=1 While x < 5: print x x=x+1 The loop iterates while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop. Use while loop when there is a condition to be met For num in range(1, 5): Print num x = [1, 2, 3, 4] For num in x: print num Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. The for loop runs for a fixed amount 21
If - else conditions An if statement consists of a boolean expression followed by one or more statements. if condition : indented. Statement. Block if temperature < 32: print('Wear a hat. ') 22
If - else conditions An if statement can be followed by an optional else statement, which executes when the boolean expression is false. if condition : indented. Statement. Block. For. True. Condition else: indented. Statement. Block. For. False. Condition newlist= [4, -1, 58, -999, 45] for item in newlist: if item > 0: print "greater than zero" else: print "less than zero" There can be at most only one else statement following if 23
If - elif conditions The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE. There can be an arbitrary number of elif statements following an if. total = int(raw_input('What is the total amount for your online shopping? ')) country = raw_input('Shipping within the US or Canada? ') if country == "US": if total <= 50: print "Shipping Costs $6. 00" elif total <= 100: print "Shipping Costs $9. 00" elif total <= 150: print "Shipping Costs $12. 00" else: 24 print "FREE"
Python - use of break Terminates the current loop and resumes execution at the next statement The break statement can be used in both while and for loops. for item in 'Help': if item == ' ': break print 'Current item : ', item Current item : H Current item : e Current item : l Current item : p 25
Objects and Object Orientation Python supports OOP and classes, but is not a full OOP language Objects are an encapsulation of variables and functions into a single entity. Objects get their variables and functions from classes. Classes are essentially a template to create your objects. A class is a way of organizing and producing objects with similar attributes and methods. 26
Classes and Objects Class: A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables). A class also defines methods, accessed via dot notation. A class must be defined before it can be instantiated. All Python objects have: A unique ID, or location in the computer’s memory A set of properties that describe the object A set of methods, or things that the object can do 27
Python Classes class Veggie (object): """A class that makes veggie objects. """ def __init__(self, name, color, shape, yummy): self. name = name Classes have one or more methods self. color = color called constructors. self. shape = shape self. yummy = yummy A constructor is a method for initializing a new instance of a class def description(self): print "I am a {0} and I am {1} and {2}". format(self. name, self. shape, self. color) def is_edible(self): if not self. yummy: print "Yuck!" else: print "Yum!" 28
Python Classes beet = Veggie("beet", "red", "round", True) beet. description() beet. is_edible() >>> I am a beet and I am round and red Yum! 29
Python Classes class Point (Object): def __init__(self, X, Y, Z, M, ID ): self. X= X self. Y = Y self. Z= Z self. M=M self. ID=ID 30
Arcpy Classes Point (arcpy) point = arcpy. Point(X=25282, Y=43770) Parameter Explanation Data Type X The X coordinate of the point. (The default value is 0. 0) Double Y The Y coordinate of the point. (The default value is 0. 0) Double Z The Z coordinate of the point. (The default value is None) Double M The M value of the point. (The default value is None) Double ID The shape ID of the point. (The default value is 0) Integer 31
Point (arcpy) import arcpy # Creates a new instance of a point object point = arcpy. Point(2000, 2500, ID=123) # Print point properties print("Point properties: ") print(" ID: {0}". format(point. ID)) print(" X: {0}". format(point. X)) print(" Y: {0}". format(point. Y)) 32
Point. Geometry (arcpy) Point. Geometry (inputs, {spatial_reference}, {has_z}, {has_m}) Explanation Data Type inputs The coordinates used to create the object. The datatype can be either Point or Array objects. Object spatial_reference The spatial reference of Spatial. Reference the new geometry. (The default value is None) has_z The Z state: True for geometry if Z is enabled and False if it is not. (The default value is False) Boolean has_m The M state: True for geometry if M is enabled and False if it is not. (The default value is False) Boolean 33
import arcpy # A list of coordinate pairs point. List = [[1, 2], [3, 5], [7, 3]] # Creates a new instance of a Point object and assigns it to the variable point = arcpy. Point() # A list to hold the Point. Geometry objects point. Geometry. List = [] # For each coordinate pair, populate the Point object and create a new Point. Geometry for pt in point. List: point. X = pt[0] point. Y = pt[1] point. Geometry = arcpy. Point. Geometry(point) point. Geometry. List. append(point. Geometry) # Create a copy of the Point. Geometry objects, by using point. Geometry. List # as input to the Copy. Features tool. arcpy. Copy. Features_management(point. Geometry. List, "c: /geometry/a. gdb/points") 34
Polygon (arcpy) Polygon (inputs, {spatial_reference}, {has_z}, {has_m}) Parameter Explanation Data Type inputs The coordinates used to create the object. The datatype can be either Point or Array objects. Object spatial_reference The spatial reference of Spatial. Reference the new geometry. (The default value is None) has_z The Z state: True for geometry if Z is enabled and False if it is not. (The default value is False) Boolean has_m The M state: True for geometry if M is enabled and False if it is not. (The default value is False) Boolean 35
Polygon (arcpy) Polygon Properties area(Read Only) The area of a polygon feature. Empty for all other Double feature types. centroid(Read Only) The true centroid if it is within or on the feature; otherwise, the label point Point is returned. Returns a point object. extent(Read and Write) The extent of the geometry. Extent first. Point(Read Only) The first coordinate point of the geometry. Point 36
Create Polygon Objects import arcpy # A list of polygons and coordinate pairs polygon_info = [[[1, 2], [1, 5], [4, 2]], [[6, 8], [5, 7], [7, 2], [9, 5]]] # A list that will hold each of the Polygon objects polys = [] for apolygon in polygon_info: # Create a Polygon object based on the array of points # Append to the list of Polygon objects polys. append( arcpy. Polygon( arcpy. Array([arcpy. Point(*coords) for coords in apolygon]))) # Persist a copy of the Polygon objects using Copy. Features arcpy. Copy. Features_management(polys, "c: /geometry/polygons. shp") 37
Python - new string Formatting Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. print "My name is {0} and my age is {1}!”. format ("Pete", 21) print(“pi={: . 2 f}". format(3. 1415926)); The {} is the placeholder for the substituted variables. If no format is specified, it will insert and format as a string. 38
String Formatting examples >>> '{0}, {1}, {2}'. format('a', 'b', 'c') 'a, b, c' >>> '{}, {}'. format('a', 'b', 'c') # 2. 7+ only 'a, b, c' >>> '{2}, {1}, {0}'. format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'. format(*'abc') # unpacking argument sequence 'c, b, a' 39
String Formatting examples The index inside of the curly braces can be followed by a colon and a format string, e. g. {0: 5 d} print("Area of polygon {} is {: . 2 f}". format(123, 457. 93682)) Area of polygon 123 is 457. 94 print("Area of polygon {0: 5 d} is {1: . 3 f}". format(123, 34. 5689)) Area of polygon 123 is 34. 569 "various precisions: {0: 6. 2 f} or {0: 6. 3 f}". format(1. 4148) 'various precisions: 1. 41 or 1. 415' d, i, signed integer f floating point decimal format s string 40
Python - new string Formatting The replacement field can start with a field_name that specifies the object whose value is to be formatted and inserted into the output instead of the replacement field. Accessing arguments by name: print " I am {adjective} today ". format(adjective=“happy") adjective="sad" print " I am {} today ". format(adjective) 41
Formatting examples >>> 'Coordinates: {latitude}, {longitude}'. format(latitude='37. 24 N', longitude='115. 81 W') 'Coordinates: 37. 24 N, -115. 81 W‘ >>> coord = {'latitude': '37. 24 N', 'longitude': '-115. 81 W'} >>> 'Coordinates: {latitude}, {longitude}'. format(**coord) 'Coordinates: 37. 24 N, -115. 81 W' 42
- Slides: 42