CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-geopandas

GeoPandas extends pandas functionality to handle geographic and geospatial data operations with GeoSeries and GeoDataFrame classes.

Pending
Overview
Eval results
Files

spatial-relationships.mddocs/

Spatial Relationships

GeoPandas provides comprehensive spatial relationship operations including spatial joins, overlays, and geometric predicates. These operations enable complex spatial analysis by testing relationships between geometries and combining datasets based on spatial criteria.

Capabilities

Spatial Predicates

Binary spatial predicates that test relationships between geometries.

class GeoSeries:
    def contains(self, other, align=True):
        """
        Test whether each geometry contains the other geometry.
        
        Parameters:
        - other: GeoSeries or single geometry
        - align: Whether to align indices before operation
        
        Returns:
        - pandas.Series: Boolean values indicating containment
        """
        ...
    
    def within(self, other, align=True):
        """
        Test whether each geometry is within the other geometry.
        
        Parameters:
        - other: GeoSeries or single geometry
        - align: Whether to align indices before operation
        
        Returns:  
        - pandas.Series: Boolean values indicating within relationship
        """
        ...
    
    def intersects(self, other, align=True):
        """
        Test whether each geometry intersects the other geometry.
        
        Parameters:
        - other: GeoSeries or single geometry
        - align: Whether to align indices before operation
        
        Returns:
        - pandas.Series: Boolean values indicating intersection
        """
        ...
    
    def touches(self, other, align=True):
        """
        Test whether each geometry touches the other geometry.
        
        Parameters:
        - other: GeoSeries or single geometry  
        - align: Whether to align indices before operation
        
        Returns:
        - pandas.Series: Boolean values indicating touch relationship
        """
        ...
    
    def crosses(self, other, align=True):
        """
        Test whether each geometry crosses the other geometry.
        
        Parameters:
        - other: GeoSeries or single geometry
        - align: Whether to align indices before operation
        
        Returns:
        - pandas.Series: Boolean values indicating crossing
        """
        ...
    
    def disjoint(self, other, align=True):
        """
        Test whether each geometry is disjoint from the other geometry.
        
        Parameters:
        - other: GeoSeries or single geometry
        - align: Whether to align indices before operation
        
        Returns:
        - pandas.Series: Boolean values indicating disjoint relationship
        """
        ...
    
    def overlaps(self, other, align=True):
        """
        Test whether each geometry overlaps the other geometry.
        
        Parameters:
        - other: GeoSeries or single geometry
        - align: Whether to align indices before operation
        
        Returns:
        - pandas.Series: Boolean values indicating overlap
        """
        ...
    
    def covers(self, other, align=True):
        """
        Test whether each geometry covers the other geometry.
        
        Parameters:
        - other: GeoSeries or single geometry
        - align: Whether to align indices before operation
        
        Returns:
        - pandas.Series: Boolean values indicating coverage
        """
        ...
    
    def covered_by(self, other, align=True):
        """
        Test whether each geometry is covered by the other geometry.
        
        Parameters:
        - other: GeoSeries or single geometry
        - align: Whether to align indices before operation
        
        Returns:
        - pandas.Series: Boolean values indicating covered_by relationship
        """
        ...
    
    def contains_properly(self, other, align=True):
        """
        Test whether each geometry properly contains the other geometry.
        
        Parameters:
        - other: GeoSeries or single geometry
        - align: Whether to align indices before operation
        
        Returns:
        - pandas.Series: Boolean values indicating proper containment
        """
        ...
    
    def geom_equals(self, other, align=True):
        """
        Test whether each geometry is geometrically equal to the other.
        
        Parameters:
        - other: GeoSeries or single geometry
        - align: Whether to align indices before operation
        
        Returns:
        - pandas.Series: Boolean values indicating geometric equality
        """
        ...
    
    def geom_equals_exact(self, other, tolerance, align=True):
        """
        Test whether each geometry is exactly equal to the other within tolerance.
        
        Parameters:
        - other: GeoSeries or single geometry
        - tolerance: Coordinate tolerance for comparison
        - align: Whether to align indices before operation
        
        Returns:
        - pandas.Series: Boolean values indicating exact equality
        """
        ...
    
    def dwithin(self, other, distance, align=True):
        """
        Test whether each geometry is within specified distance of the other.
        
        Parameters:
        - other: GeoSeries or single geometry
        - distance: Maximum distance threshold
        - align: Whether to align indices before operation
        
        Returns:
        - pandas.Series: Boolean values indicating within-distance relationship
        """
        ...
    
    def covered_by(self, other, align=True):
        """
        Test whether each geometry is covered by the other geometry.
        
        Parameters:
        - other: GeoSeries or single geometry
        - align: Whether to align indices before operation
        
        Returns:
        - pandas.Series: Boolean values indicating covered relationship
        """
        ...

Distance Operations

Functions for calculating distances between geometries.

class GeoSeries:
    def distance(self, other, align=True):
        """
        Calculate distance to other geometry.
        
        Parameters:
        - other: GeoSeries or single geometry
        - align: Whether to align indices before operation
        
        Returns:
        - pandas.Series: Distance values (units depend on CRS)
        """
        ...

Set Operations

Geometric set operations that combine geometries.

class GeoSeries:
    def intersection(self, other, align=True):
        """
        Calculate intersection with other geometry.
        
        Parameters:
        - other: GeoSeries or single geometry
        - align: Whether to align indices before operation
        
        Returns:
        - GeoSeries: Intersection geometries
        """
        ...
    
    def union(self, other, align=True):
        """
        Calculate union with other geometry.
        
        Parameters:
        - other: GeoSeries or single geometry
        - align: Whether to align indices before operation
        
        Returns:
        - GeoSeries: Union geometries
        """
        ...
    
    def difference(self, other, align=True):
        """
        Calculate difference from other geometry.
        
        Parameters:
        - other: GeoSeries or single geometry
        - align: Whether to align indices before operation
        
        Returns:
        - GeoSeries: Difference geometries
        """
        ...
    
    def symmetric_difference(self, other, align=True):
        """
        Calculate symmetric difference with other geometry.
        
        Parameters:
        - other: GeoSeries or single geometry
        - align: Whether to align indices before operation
        
        Returns:
        - GeoSeries: Symmetric difference geometries
        """
        ...
    
    def unary_union(self):
        """
        Calculate union of all geometries in the series.
        
        Returns:
        - shapely.geometry: Single unified geometry
        """
        ...

Spatial Joins

Functions for joining datasets based on spatial relationships.

def sjoin(left_df, right_df, how='inner', predicate='intersects', lsuffix='left', rsuffix='right', **kwargs):
    """
    Spatial join of two GeoDataFrames.
    
    Parameters:
    - left_df: Left GeoDataFrame
    - right_df: Right GeoDataFrame  
    - how: Type of join ('left', 'right', 'outer', 'inner')
    - predicate: Spatial predicate ('intersects', 'within', 'contains', 'overlaps', 'crosses', 'touches')
    - lsuffix: Suffix for left DataFrame column conflicts
    - rsuffix: Suffix for right DataFrame column conflicts
    - **kwargs: Additional parameters
    
    Returns:
    - GeoDataFrame: Spatially joined data
    """
    ...

def sjoin_nearest(left_df, right_df, how='inner', max_distance=None, lsuffix='left', rsuffix='right', distance_col=None, **kwargs):
    """
    Spatial join to nearest geometries.
    
    Parameters:
    - left_df: Left GeoDataFrame
    - right_df: Right GeoDataFrame
    - how: Type of join ('left', 'right', 'outer', 'inner')
    - max_distance: Maximum distance for nearest neighbor search
    - lsuffix: Suffix for left DataFrame column conflicts
    - rsuffix: Suffix for right DataFrame column conflicts
    - distance_col: Name for distance column in result
    - **kwargs: Additional parameters
    
    Returns:
    - GeoDataFrame: Spatially joined data with nearest neighbors
    """
    ...

Overlay Operations

Functions for geometric overlay operations between datasets.

def overlay(df1, df2, how='intersection', keep_geom_type=None, make_valid=True):
    """
    Perform geometric overlay operation between two GeoDataFrames.
    
    Parameters:
    - df1: First GeoDataFrame
    - df2: Second GeoDataFrame
    - how: Overlay operation ('intersection', 'union', 'identity', 'symmetric_difference', 'difference')
    - keep_geom_type: Whether to keep only original geometry types
    - make_valid: Whether to make invalid geometries valid before operation
    
    Returns:
    - GeoDataFrame: Result of overlay operation
    """
    ...

Clipping Operations

Functions for clipping geometries by masks.

def clip(gdf, mask, keep_geom_type=False, sort=False):
    """
    Clip geometries to the boundary of another geometry.
    
    Parameters:
    - gdf: GeoDataFrame to clip
    - mask: Geometry or GeoDataFrame to use as clipping mask
    - keep_geom_type: Whether to keep only original geometry types
    - sort: Whether to sort the result by index
    
    Returns:
    - GeoDataFrame: Clipped geometries
    """
    ...

Geocoding Operations

Functions for converting between addresses and coordinates.

def geocode(strings, provider=None, **kwargs):
    """
    Geocode addresses to coordinates.
    
    Parameters:
    - strings: List or Series of address strings
    - provider: Geocoding provider name
    - **kwargs: Provider-specific parameters
    
    Returns:
    - GeoDataFrame: Geocoded addresses with geometry points
    """
    ...

def reverse_geocode(points, provider=None, **kwargs):
    """
    Reverse geocode coordinates to addresses.
    
    Parameters:
    - points: GeoSeries of Point geometries or array-like coordinates
    - provider: Geocoding provider name
    - **kwargs: Provider-specific parameters
    
    Returns:
    - GeoDataFrame: Reverse geocoded coordinates with address information
    """
    ...

Geometry Utilities

Utility functions for working with collections of geometries.

def collect(x, multi=False):
    """
    Collect geometries into a GeometryCollection or Multi-geometry.
    
    Parameters:
    - x: Array-like of geometries
    - multi: Whether to create Multi-geometry instead of GeometryCollection
    
    Returns:
    - shapely.geometry: GeometryCollection or Multi-geometry
    """
    ...

Usage Examples

Spatial Predicates

import geopandas as gpd
from shapely.geometry import Point, Polygon

# Create sample data
points = gpd.GeoDataFrame({
    'id': [1, 2, 3, 4],
    'geometry': [Point(1, 1), Point(3, 3), Point(5, 1), Point(2, 4)]
})

polygons = gpd.GeoDataFrame({
    'name': ['A', 'B'],
    'geometry': [
        Polygon([(0, 0), (2, 0), (2, 2), (0, 2)]),  # Square A
        Polygon([(3, 2), (5, 2), (5, 4), (3, 4)])   # Square B
    ]
})

# Test spatial relationships
polygon_a = polygons.geometry.iloc[0]

# Points within polygon A
within_a = points.geometry.within(polygon_a)
print(f"Points within A: {points[within_a]['id'].tolist()}")

# Points intersecting polygon A
intersect_a = points.geometry.intersects(polygon_a)
print(f"Points intersecting A: {points[intersect_a]['id'].tolist()}")

# Test between all combinations
for i, poly in polygons.iterrows():
    contained = points.geometry.within(poly['geometry'])
    print(f"Points in {poly['name']}: {points[contained]['id'].tolist()}")

Distance Calculations

# Calculate distances between points and polygons
distances_to_a = points.geometry.distance(polygons.geometry.iloc[0])
print(f"Distances to polygon A: {distances_to_a}")

# Find nearest polygon for each point
distances_to_all = []
for _, poly in polygons.iterrows():
    dist = points.geometry.distance(poly['geometry'])
    distances_to_all.append(dist)

# Create distance matrix
import pandas as pd
distance_matrix = pd.DataFrame(distances_to_all, 
                              index=polygons['name'], 
                              columns=points['id']).T
print("Distance matrix:")
print(distance_matrix)

# Find nearest polygon for each point
nearest_polygon = distance_matrix.idxmin(axis=1)
print(f"Nearest polygon for each point: {nearest_polygon}")

Spatial Joins

# Join points to polygons they fall within
joined = gpd.sjoin(points, polygons, how='left', predicate='within')
print("Points joined to containing polygons:")
print(joined[['id', 'name']])

# Join points to all intersecting polygons
joined_intersects = gpd.sjoin(points, polygons, how='left', predicate='intersects')
print("Points joined to intersecting polygons:")
print(joined_intersects[['id', 'name']])

# Join to nearest polygon regardless of containment
joined_nearest = gpd.sjoin_nearest(points, polygons, how='left')
print("Points joined to nearest polygons:")
print(joined_nearest[['id', 'name']])

# Join with distance threshold
joined_near = gpd.sjoin_nearest(points, polygons, how='left', 
                               max_distance=1.0, distance_col='distance')
print("Points within 1.0 unit of polygons:")
print(joined_near[['id', 'name', 'distance']].dropna())

Set Operations

# Create overlapping polygons
poly1 = gpd.GeoDataFrame({
    'id': [1],
    'geometry': [Polygon([(0, 0), (3, 0), (3, 3), (0, 3)])]
})

poly2 = gpd.GeoDataFrame({
    'id': [2], 
    'geometry': [Polygon([(2, 2), (5, 2), (5, 5), (2, 5)])]
})

# Calculate geometric intersections
intersection = poly1.geometry.intersection(poly2.geometry.iloc[0])
union = poly1.geometry.union(poly2.geometry.iloc[0])
difference = poly1.geometry.difference(poly2.geometry.iloc[0])
sym_diff = poly1.geometry.symmetric_difference(poly2.geometry.iloc[0])

print(f"Intersection area: {intersection.iloc[0].area}")
print(f"Union area: {union.iloc[0].area}")
print(f"Difference area: {difference.iloc[0].area}")
print(f"Symmetric difference area: {sym_diff.iloc[0].area}")

Overlay Operations

# Perform overlay operations
intersection_overlay = gpd.overlay(poly1, poly2, how='intersection')
union_overlay = gpd.overlay(poly1, poly2, how='union') 
difference_overlay = gpd.overlay(poly1, poly2, how='difference')

print("Intersection overlay:")
print(intersection_overlay[['id_1', 'id_2', 'geometry']])

print("Union overlay:")
print(union_overlay[['id_1', 'id_2', 'geometry']])

# Identity overlay (keeps all of first dataset)
identity_overlay = gpd.overlay(poly1, poly2, how='identity')
print("Identity overlay:")
print(identity_overlay)

Clipping Operations

# Create data to clip
lines = gpd.GeoDataFrame({
    'id': [1, 2, 3],
    'geometry': [
        LineString([(0, 1), (4, 1)]),    # Crosses polygon
        LineString([(1, 0), (1, 4)]),    # Crosses polygon  
        LineString([(6, 0), (6, 4)])     # Outside polygon
    ]
})

# Clip lines to polygon boundary
clipping_polygon = Polygon([(0.5, 0.5), (3.5, 0.5), (3.5, 3.5), (0.5, 3.5)])
clipped_lines = gpd.clip(lines, clipping_polygon)

print("Original lines:", len(lines))
print("Clipped lines:", len(clipped_lines))
print("Clipped geometries:")
for i, geom in enumerate(clipped_lines.geometry):
    print(f"  Line {i+1}: {geom}")

Complex Spatial Analysis

# Load real world data
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
cities = gpd.read_file(gpd.datasets.get_path('naturalearth_cities'))

# Find cities within each country
cities_in_countries = gpd.sjoin(cities, world, how='left', predicate='within')

# Count cities per country
cities_per_country = (cities_in_countries
                     .groupby('name_right')
                     .size()
                     .sort_values(ascending=False))
print("Top 10 countries by number of cities:")
print(cities_per_country.head(10))

# Find countries that border the ocean (simplified)
# Create buffer around all land
land_union = world.geometry.unary_union
ocean_buffer = land_union.buffer(0.1)  # Small buffer

# Countries touching the buffer are coastal
coastal_countries = world[world.geometry.touches(ocean_buffer)]
print(f"Number of coastal countries: {len(coastal_countries)}")

# Calculate distance from each city to nearest country border
country_boundaries = world.geometry.boundary
cities['dist_to_border'] = cities.geometry.apply(
    lambda city: min(city.distance(boundary) for boundary in country_boundaries)
)
print("Cities farthest from any border:")
print(cities.nlargest(5, 'dist_to_border')[['name', 'dist_to_border']])

Install with Tessl CLI

npx tessl i tessl/pypi-geopandas

docs

coordinate-systems.md

core-data-structures.md

file-io.md

geometric-operations.md

index.md

spatial-relationships.md

testing-utilities.md

visualization.md

tile.json