Count observations by region in one deferred query#

How many non-null observation IDs occur in each region group after a spatial join? Build the join and grouping first, then collect them together.

Select the geometry#

Start in cugeo-geometry/ with working Geometry Python bindings. Select geom on each input for the spatial predicate.

from pathlib import Path
import cugeo.geometry as geo

root = Path('crates/execution/tests/fixtures/materialized-joins')
points = geo.LazyFrame(
    geo.table_from_file(root / 'join-points.parquet')
).set_geometry('geom')
regions = geo.LazyFrame(
    geo.table_from_file(root / 'join-regions.parquet')
).set_geometry('geom')

Build the grouped query#

Keep points on the left so an observation without a region partner retains a row. An observation with several region partners can contribute several joined occurrences. The join and grouping describe work without executing it.

joined = geo.LazyFrame.sjoin(points, regions, how='left', predicate='within')
grouped = joined.groupby('zone_id').agg(valid=('id', 'count'))

Collect the result#

Execute the join and aggregation together in a session.

with geo.Session() as session:
    result = grouped.collect(session=session)

Read the five groups#

Print the columns and sort the rows for display.

print(result.columns)
print(sorted(result.rows, key=lambda r: (r[0] is None, r[0])))
('zone_id', 'valid')
[(1, 6), (2, 1), (3, 1), (6, 6), (None, 12)]

Zone 1 has seven joined occurrences, six of which have an ID, so count gives six. A group’s .size() counts every occurrence, including those with a null ID. The final pair says that 12 occurrences in the null-zone group have an ID. A matched region can itself have a null zone_id, so that count alone does not say how many observations lacked a partner.