Assign locations to districts with dataframes#
Find which districts intersect each location. You’ll use a left intersection join to keep every location, including one outside all districts and one inside two districts.
Prepare the layers#
With eager Geometry available, start in the cugeo-geometry checkout beside the supplied files in docs/site/guide/tutorial/assets/. Both use WKB primary geometry named geom and the projected CRS EPSG:32631.
Layer |
Label |
Geometry |
|---|---|---|
Locations |
|
Point |
Locations |
|
Point |
Locations |
|
Point |
Districts |
|
Closed rectangle with opposite corners |
Districts |
|
Closed rectangle with opposite corners |
Join and inspect the assignments#
From cugeo-geometry/, open both layers in one session, inspect their geometry and CRS, and keep the session live while you inspect the result.
from pathlib import Path
import cugeo.geometry as geo
assets = Path('docs/site/guide/tutorial/assets')
with geo.Session() as session:
locations = geo.read_file(assets / 'locations.parquet', session=session)
districts = geo.read_file(assets / 'districts.parquet', session=session)
print(locations.active_geometry_name, locations.crs)
print(districts.active_geometry_name, districts.crs)
assigned = locations.sjoin(districts, how='left', predicate='intersects')
pairs = list(zip(
assigned['location_id'].to_arrow().to_pylist(),
assigned['district_id'].to_arrow().to_pylist(),
))
print(sorted(pairs, key=lambda pair: (pair[0], pair[1] or '')))
The checked run printed the following output.
geom EPSG:32631
geom EPSG:32631
[('A', 'West'), ('B', 'East'), ('B', 'West'), ('C', None)]
The left occurrences retain their order. Sorting the display puts B’s district labels in alphabetical order. B lies inside both rectangles, so both district labels are answers. C lies outside both, and the left join keeps it with no district label. To see what happens when a point touches a district edge, read why a spatial join returns these rows.