4

Using this example dataset of country geometries, I seem to get a different result on whether or not the USA and Mexico intersect when I do the calculation with GeoPandas as opposed to directly with Fiona and Shapely (upon which Geopandas depends). I am reasonably experienced with Fiona and Shapely, but quite new to GeoPandas - does anyone know why this might be?

Consider the following code snippet:

from geopandas import read_file

# load the shapefile of countries
world = read_file('TM_WORLD_BORDERS-0.3.shp')

# extract usa and mexico
usa = world[ (world.ISO3 == 'USA') ]
mexico = world[ (world.ISO3 == 'MEX') ]

# test intersection
print(usa.intersects(mexico))

This gives:

119    False
208    False
dtype: bool

However, if I do the same thing directly with Fiona and Shapely:

from fiona import open
from shapely.geometry import shape

# load the shapefile of countries
with open('TM_WORLD_BORDERS-0.3.shp') as countries:

    # extract usa and mexico
    for feat in countries:
        if feat['properties']['ISO3'] == 'USA':
            usa = shape(feat['geometry'])
        elif feat['properties']['ISO3'] == 'MEX':
            mexico = shape(feat['geometry'])

# test intersection
print(usa.intersects(mexico))

Then I get:

True

Clearly, I would expect both code snippets to evaluate to True. I had wondered if Geopandas handled MultiPolygons differently (as USA is a MultiPolygon, whereas Mexico is a Polygon), but I can't seem to get a positive intersection by isolating the individual polygon either.

4

In the first case, using geopandas you are comparing two GeoDataFrames. If you pass GDFs to intersects, geopandas aligns them based on the index as it expects array-to-array operation. Then it compares USA to empty and Mexico to empty, hence gives False twice. To align Mexico to USA, you can reset index to get 0 for both. Then you'll get True as expected:

usa.reset_index().intersects(mexico.reset_index())

In the second case, both usa and mexico are shapely geometries, so you are comparing geometries directly. You can do the same using geopandas, you just need to extract geometries only from GeoDataFrame to get to the same point. Then you'll have exactly the same objects.

usa = world[ (world.ISO3 == 'USA') ]['geometry'].iloc[0]
mexico = world[ (world.ISO3 == 'MEX') ]['geometry'].iloc[0]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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