Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I'm new to python and arcpy but I've been trying to learn how to run geoprocessing tools using arcpy. I have (for this example) 2 shapefiles, a and b, which are both polygons. From plotting them in arcMap, I know that b is found entirely within a.

I would like to write a script that will take these two shapefiles and give me a True/False response about whether or not one polygon contains the other. I was thinking of using the arcpy.Geometry.contains() function.

I have the following:

>>> a_shp="C:\\Data\\shapefile_a.shp"
>>> b_shp="C:\\Data\\shapefile_b.shp"

>>> #read in as geometry
>>> a=arcpy.CopyFeatures_management(a_shp, arcpy.Geometry())
>>> b=arcpy.CopyFeatures_management(b_shp, arcpy.Geometry())

>>> arcpy.Geometry.contains(a[0],b[0])
False
>>> arcpy.Geometry.contains(b[0],a[0]) #maybe I got the order wrong? Trying the other order
False

>>> #Maybe I'm getting the syntax wrong, trying something else
>>> a[0].contains(b[0])
False
>>> b[0].contains(a[0])
False

I get no error messages but clearly something isn't working properly. Am I doing this right? Any pointers would be greatly appreciated. Thank you!

share|improve this question

migrated from stackoverflow.com Oct 10 '11 at 10:52

This question came from our site for professional and enthusiast programmers.

    
This strategy should work as well as Jason Scheirer's method. I have used geometry object outputs before. Did you get the correct output from Jason's method? The correct syntax is a[0].contains(b[0]) or conversely b[0].within(a[0]). I am not certain though that you can reference by subscripting on a geometry list. –  blord-castillo Oct 10 '11 at 11:08
add comment

1 Answer 1

up vote 3 down vote accepted

a and b will be result objects in this case. You'll need to open two search cursors and pull the shape field off of each to use the contains operator. Something like this:

for row1 in arcpy.SearchCursor(shapefile1):
    for row2 in arcpy.SearchCursor(shapefile2):
        if row1.shape.contains(row2.shape):
            return True
share|improve this answer
    
Thanks Jason! That works! I guess I just need to get a better understanding of arcpy... –  user983332 Oct 7 '11 at 19:16
    
These helpfiles should be helpful: –  blord-castillo Oct 10 '11 at 10:58
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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