Ibis for Spatial Data Explained: Dataframe Code That DuckDB Runs as SQL
On this page
Problem statement
Counting Auckland's 623,445 Overture Maps buildings into its 167 suburbs gives the same answer in GeoPandas and in Ibis on DuckDB: Henderson, 20,218 buildings. GeoPandas peaked at 1,521 MB of memory and Ibis at 442 MB, in about the same time. The difference is where the work happens. Ibis never holds the data: its methods build an expression that it compiles to one SQL query, which DuckDB runs. This page shows that path step by step, what it costs and saves, and where spatial code stops being portable.
Quick answer
An Ibis table is a description of a query. Methods build it up without reading anything, ibis.to_sql shows the SQL, and execute() runs it in DuckDB and returns a (Geo)DataFrame:
per_suburb = (bldg.join(subs, bldg.c.within(subs.g))
.group_by("name").aggregate(buildings=_.count(), m2=_.m2.sum())
.order_by(ibis.desc("buildings")))
print(type(per_suburb).__name__, "Β·", len(ibis.to_sql(per_suburb).splitlines()), "lines of SQL")
print(per_suburb.limit(3).execute().round(0).to_string(index=False))
Table Β· 46 lines of SQL
name buildings m2
Henderson 20218 3312176.0
Papatoetoe 17234 2681066.0
Manurewa 15006 2006769.0
per_suburb is a Table, but it holds no rows: it is the 46 lines of SQL its methods describe. Only execute() runs it. Henderson has the most buildings, 20,218 with 3,312,176 mΒ² of footprint, ahead of Papatoetoe and Manurewa.
Expression, compilation, execution
1. An expression reads nothing
t0 = time.perf_counter()
expr = bldg.filter(_.m2 > 1000).count()
print(f"built in {(time.perf_counter() - t0) * 1000:.1f} ms: {type(expr).__name__}")
t0 = time.perf_counter()
n = expr.execute()
print(f"executed in {time.perf_counter() - t0:.2f} s β {n:,} buildings over 1,000 mΒ²")
built in 0.6 ms: IntegerScalar
executed in 0.25 s β 7,917 buildings over 1,000 mΒ²
Building a filter and count over 623,445 buildings took 0.6 ms, because nothing was read; the result is an IntegerScalar expression, not a number. Executing it took 0.25 s and found 7,917 buildings with a footprint over 1,000 mΒ². Every Ibis script has this split: the lines that describe the work are instant, and the work happens in the call that asks for a result.
2. One query, however many steps
sql = ibis.to_sql(per_suburb)
print("SELECT statements:", sql.count("SELECT"), "Β· spatial functions:", sorted(set(re.findall(r"ST_[A-Z]+", sql))))
SELECT statements: 7 Β· spatial functions: ['ST_AREA', 'ST_CENTROID', 'ST_TRANSFORM', 'ST_WITHIN']
Two reads, reprojection, area, centroid, join, group and sort became seven nested SELECTs calling four spatial functions. Ibis computes no geometry; every method on this page ended up as one of these four DuckDB functions.
3. The same job in GeoPandas and in Ibis, measured
JOB = {
"GeoPandas": """
import geopandas as gpd
b = gpd.read_parquet(BUILDINGS).to_crs(2193)
s = gpd.read_parquet(SUBURBS).to_crs(2193)
b["m2"] = b.area
b["geometry"] = b.centroid
j = gpd.sjoin(b[["m2", "geometry"]], s[["name", "geometry"]], predicate="within")
r = j.groupby("name").agg(buildings=("m2", "size"), m2=("m2", "sum")).reset_index()
""",
"Ibis + DuckDB": """
import ibis
from ibis import _
con = ibis.duckdb.connect()
con.raw_sql("set enable_progress_bar = false")
read = lambda f: con.sql(f"select * replace (geometry::GEOMETRY as geometry) from read_parquet('{f}')")
b = read(BUILDINGS).select(m2=_.geometry.convert("EPSG:4326", "EPSG:2193").area(),
c=_.geometry.convert("EPSG:4326", "EPSG:2193").centroid())
s = read(SUBURBS).select("name", g=_.geometry.convert("EPSG:4326", "EPSG:2193"))
r = b.join(s, b.c.within(s.g)).group_by("name").aggregate(buildings=_.count(), m2=_.m2.sum()).execute()
""",
}
TAIL = """
top = r.sort_values("buildings", ascending=False).iloc[0]
hwm = next(int(l.split()[1]) for l in open("/proc/self/status") if l.startswith("VmHWM"))
print(f"{top['name']}|{int(top.buildings)}|{top.m2:.0f}|{time.perf_counter() - T0:.2f}|{hwm / 1024:.0f}")
"""
for label, body in JOB.items():
head = f"import time\nT0 = time.perf_counter()\nBUILDINGS, SUBURBS = {BUILDINGS!r}, {SUBURBS!r}\n"
out = subprocess.run([sys.executable, "-c", head + body + TAIL], capture_output=True, text=True, check=True).stdout
name, n, m2, secs, mb = out.strip().splitlines()[-1].split("|")
print(f"{label:14} top suburb {name}, {int(n):,} buildings, {int(m2):,} mΒ² {secs} s, peak memory {int(mb):,} MB")
GeoPandas top suburb Henderson, 20,218 buildings, 3,312,176 mΒ² 3.90 s, peak memory 1,521 MB
Ibis + DuckDB top suburb Henderson, 20,218 buildings, 3,312,176 mΒ² 3.48 s, peak memory 442 MB
Each version ran in its own process, so each peak (VmHWM) is its own. Time was close, 3.90 s against 3.48 s. Memory was not: 1,521 MB for GeoPandas, which materialises every footprint, its projected copy and its centroid as Python objects, against 442 MB for DuckDB, which keeps the 167 groups and passes the buildings through. Timings and peaks move a little between runs; the counts do not.
4. The same expression for another engine
for dialect in ["duckdb", "postgres", "snowflake"]:
try:
sql = ibis.to_sql(per_suburb, dialect=dialect)
print(f"{dialect:9} {len(sql.splitlines())} lines; join: {next(l.strip() for l in sql.splitlines() if 'ST_WITHIN' in l)}")
except OperationNotDefinedError as error:
print(f"{dialect:9} {type(error).__name__}: {error}")
duckdb 46 lines; join: ON ST_WITHIN("t5"."c", "t4"."g")
postgres OperationNotDefinedError: Compilation rule for 'GeoConvert' operation is not defined
snowflake OperationNotDefinedError: Compilation rule for 'GeoConvert' operation is not defined
Ibis's promise is that one expression runs on many engines, and for tabular work it largely holds. For spatial work it holds less well: this expression compiles for DuckDB, but not for PostgreSQL or Snowflake, because convert is defined only on DuckDB, and the other backends reproject with transform, which DuckDB lacks (that asymmetry). Spatial Ibis code is written for one backend at a time.
Deferred columns and drifting dependencies
The data used on this page
623,445 Overture Maps building footprints and 167 suburbs (macrohood division areas) for Auckland, release 2026-11-18.0, from a saved copy; ODbL 1.0, Β© OpenStreetMap contributors, Overture Maps Foundation. A building counts in the suburb holding its centroid.
import re
import subprocess
import sys
import time
from pathlib import Path
import duckdb
import ibis
import pandas as pd
import requests
import sqlglot
from ibis import _
from ibis.common.exceptions import OperationNotDefinedError
Path("data").mkdir(exist_ok=True)
BASE = "https://data.spatialworkflow.io/"
for name in ["overture-auckland-suburbs-2026-11-18.0.parquet", "overture-auckland-buildings-2026-11-18.0.parquet"]:
if not Path(f"data/{name}").exists(): # buildings: 80 MB
with requests.get(BASE + name, stream=True, timeout=600) as r:
r.raise_for_status()
with open(f"data/{name}", "wb") as f:
for chunk in r.iter_content(1 << 20):
f.write(chunk)
BUILDINGS = str(Path("data/overture-auckland-buildings-2026-11-18.0.parquet").resolve())
SUBURBS = str(Path("data/overture-auckland-suburbs-2026-11-18.0.parquet").resolve())
con = ibis.duckdb.connect()
con.raw_sql("set enable_progress_bar = false")
# the cast is for Ibis 12, which cannot read DuckDB's GEOMETRY('OGC:CRS84') type (see /ibis-keyerror-ogc-crs84/)
read = lambda f: con.sql(f"select * replace (geometry::GEOMETRY as geometry) from read_parquet('{f}')")
bldg = read(BUILDINGS).select(m2=_.geometry.convert("EPSG:4326", "EPSG:2193").area(),
c=_.geometry.convert("EPSG:4326", "EPSG:2193").centroid())
subs = read(SUBURBS).select("name", g=_.geometry.convert("EPSG:4326", "EPSG:2193"))
print(f"{bldg.count().execute():,} buildings, {subs.count().execute()} suburbs Β· ibis {ibis.__version__}, "
f"duckdb {duckdb.__version__}, sqlglot {sqlglot.__version__}")
623,445 buildings, 167 suburbs Β· ibis 12.0.0, duckdb 1.5.5, sqlglot 30.35.0
Example 1: _ refers to the table at that step
step = bldg.mutate(big=_.m2 > 1000).filter(_.big) # `_` is the mutated table, which has `big`
try:
bldg.mutate(big=bldg.m2 > 1000).filter(bldg.big) # `bldg` never had a `big` column
except AttributeError as error:
print(f"{type(error).__name__}: {str(error).splitlines()[0][:70]}")
print(f"with _: {step.count().execute():,} buildings over 1,000 mΒ²")
AttributeError: 'Table' object has no attribute 'big'
with _: 7,917 buildings over 1,000 mΒ²
_ is a deferred reference: it stands for whatever table the method is called on at that step. After mutate(big=...) the table has a big column, and _.big finds it. bldg.big names the original table, which never had one, so Ibis raises AttributeError while building the expression. Use _ inside chains, and a named table only to pick a side, as in a join condition.
Example 2: a dependency Ibis does not pin
try:
con.create_table("lookup", pd.DataFrame({"name": ["Henderson"], "board": ["Henderson-Massey"]}))
print("create_table from a DataFrame: works")
except duckdb.ParserException as error:
print(f"create_table from a DataFrame, sqlglot {sqlglot.__version__}: {type(error).__name__}: {error}")
lookup = ibis.memtable({"name": ["Henderson"], "board": ["Henderson-Massey"]})
print("memtable instead:", per_suburb.join(lookup, "name").select("name", "board", "buildings").execute().to_dict("records"))
create_table from a DataFrame, sqlglot 30.35.0: ParserException: Parser Error: syntax error at end of input
memtable instead: [{'name': 'Henderson', 'board': 'Henderson-Massey', 'buildings': 20218}]
Ibis compiles through sqlglot, which it requires at any version from 23.4 up, so a fresh install gets the newest. With sqlglot 30.35.0, con.create_table from a pandas DataFrame fails with a ParserException from DuckDB, because the SQL Ibis builds for it is cut short. ibis.memtable takes another route and works: the lookup joins to Henderson's 20,218 buildings. Pin the versions a working Ibis script was run with, Ibis, DuckDB and sqlglot together.
When Ibis is the right layer
Ibis is worth adding when the data is larger than memory comfortably holds and you think in dataframes: it puts DuckDB's streaming engine under code that reads like GeoPandas, at a third of the memory on this page's job. It is also worth it when a pipeline has to stay as a query, for example to run against files in object storage, where pulling every row into Python is the cost. It is not worth it for data that fits in memory and needs shapely-level control, plotting or row-by-row Python: GeoPandas does those directly, and at this page's size it was no slower. Most real projects use both. Ibis cuts the large tables down to the rows that matter, and GeoPandas takes the result from there.
Internal links
- How to rewrite a GeoPandas workflow in Ibis β the translation, call by call, checked row for row
- How to see the SQL behind an Ibis spatial query β reading the compiled query and its plan
- Fixing KeyError: 'OGC:CRS84' when Ibis reads GeoParquet β the cast in every read on this page
- DuckDB spatial explained β the engine underneath, without Ibis
FAQ
Is Ibis a replacement for GeoPandas?
No. It replaces the part of a GeoPandas script that moves and summarises large tables. The results come back as a GeoDataFrame, and anything that needs one, plotting, shapely operations, writing a shapefile, carries on in GeoPandas.
Does Ibis need DuckDB?
DuckDB is its default backend and the one with the most spatial support. Ibis also has PostgreSQL (with PostGIS), BigQuery, Snowflake and others, but which geometry methods compile differs by backend, as step 4 shows.