0

I have an array of points by using getPart on each of the four polygons in the shapefile. I am trying to figure out a way to create a list of x and y coordinates in my for loop and name them xCoords and yCoords so I can plug them into my functions to calculate the perimeter. For some reason, I can't seem to make a list that separates the x and y points... any ideas?

Note: When I print point.X or point.Y, it gives me one coordinate. I know that I have to write some code in my for loop to get separate lists of x and y coordinates for each polygon, I'm just not sure how to.

import arcpy, os
from arcpy import env
from arcpy.sa import *
from math import *


env.workspace = r"H:\GEOG 4303\cho_lab4\lab4\data"
env.overwriteOutput = 1

theme = 'watersheds_3D.shp'
DEM = 'demlab4'

cursor = arcpy.da.SearchCursor(theme, ["SHAPE@", "Id"])
for row in cursor:
    array = arcpy.Array()
    print("Polygon Id: {0}".format(row[1]))
    for Id in row[0].getPart():
        print("Polygon coordinates: {0}".format(Id.count))
        for point in Id:
            print("X: {0}, Y: {1}".format(point.X, point.Y))
            array.add(arcpy.Point(point.X, point.Y))
        print array
1

1 Answer 1

1

A bit unclear what you want but you should be able to use collections.defaultdict:

Using list as the default_factory, it is easy to group a sequence of key-value pairs into a dictionary of lists

import arcpy
from collections import defaultdict
fc = r"C:\folder\shapefile.shp"
dx = defaultdict(list)
dy = defaultdict(list)

with arcpy.da.SearchCursor(fc,['OID@','SHAPE@']) as cursor:
    for row in cursor:
        array1=row[1].getPart()
        for vertice in range(row[1].pointCount):
            pnt=array1.getObject(0).getObject(vertice)
            dx[row[0]].append(pnt.X)
            dy[row[0]].append(pnt.Y)

You will now have two dictionaries with ObjectID as key and a list of coordinates for each polygon as values . For example all the vertices for the first polygon (objectid 0) as lists:

print(dx[0])
print(dy[0])
>>[800000.0, 800000.0, 700000.0, 700000.0, 800000.0]
>>[7400000.0, 7300000.0, 7300000.0, 7400000.0, 7400000.0]

Start and end coordinates are the same. Can be removed if you want.

Iterating:

for oid in dx:
    print(dx[oid], dy[oid])
>>[800000.0, 800000.0, 700000.0, 700000.0, 800000.0] [7400000.0, 7300000.0, 7300000.0, 7400000.0, 7400000.0]
>>[800000.0, 800000.0, 700000.0, 700000.0, 800000.0] [7400000.0, 7300000.0, 7300000.0, 7400000.0, 7400000.0]
>>...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.