Files
solon/scripts/places/zurich-postcode-quarters.py
CatoandClaude 0f7394030a feat(places): 8053 is Witikon: the City of Zürich's postcodes by quarter (#664)
Every official address in the City of Zürich (swisstopo's register of
building addresses) placed in the city's statistical quarters and
counted per postcode: 98.6 % of 8053's addresses are in Witikon. The
table (data/places/switzerland/zurich-postcode-quarters.csv) is made by
scripts/places/zurich-postcode-quarters.py and imported as a postcode
source. A postcode search puts a quarter holding most of a postcode
before the city it lies in.


Claude-Session: https://claude.ai/code/session_019MDtmvTCDbJAYNKQpNyKzz

Co-authored-by: Claude <noreply@anthropic.com>
2026-12-01 21:51:55 +01:00

94 lines
3.8 KiB
Python

"""
Which of the City of Zürich's statistical quarters each of its postcodes covers,
and the share of the postcode's addresses in each: the swisstopo address
register's every address in the city, placed in the city's own quarter
boundaries. Writes data/places/switzerland/zurich-postcode-quarters.csv.
Why: Solon's postcode directory (swisstopo-postcode-localities) names only the
commune, so 8053 led to "Zürich" although 98.6 % of its addresses are in
Witikon. Run by hand when either source changes (stdlib only):
python3 -I scripts/places/zurich-postcode-quarters.py
Sources (both open data):
- swisstopo, official directory of building addresses (amtliches
Gebäudeadressverzeichnis), CSV in LV95, rows with ADR_STATUS "real".
- City of Zürich, statistical quarters (geo_statistische_quartiere), CC0, in LV95.
"""
import csv
import collections
import io
import json
import os
import sys
import urllib.request
import zipfile
ADDRESSES = "https://data.geo.admin.ch/ch.swisstopo.amtliches-gebaeudeadressverzeichnis/amtliches-gebaeudeadressverzeichnis_ch/amtliches-gebaeudeadressverzeichnis_ch_2056.csv.zip"
QUARTERS = "https://www.ogd.stadt-zuerich.ch/wfs/geoportal/Statistische_Quartiere?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=adm_statistische_quartiere_map&OUTPUTFORMAT=GeoJSON&SRSNAME=EPSG:2056"
CITY = "261" # the FSO number of the City of Zürich
OUT = os.path.join(os.path.dirname(__file__), "..", "..", "data", "places", "switzerland", "zurich-postcode-quarters.csv")
def fetch(url):
with urllib.request.urlopen(url, timeout=600) as r:
return r.read()
def in_ring(x, y, ring):
inside, j = False, len(ring) - 1
for i in range(len(ring)):
xi, yi = ring[i][0], ring[i][1]
xj, yj = ring[j][0], ring[j][1]
if (yi > y) != (yj > y) and x < (xj - xi) * (y - yi) / (yj - yi) + xi:
inside = not inside
j = i
return inside
def main():
quarters = []
for f in json.loads(fetch(QUARTERS))["features"]:
g = f["geometry"]
polys = [g["coordinates"]] if g["type"] == "Polygon" else g["coordinates"]
xs = [p[0] for poly in polys for p in poly[0]]
ys = [p[1] for poly in polys for p in poly[0]]
quarters.append((f["properties"]["qnr"], polys, (min(xs), max(xs), min(ys), max(ys))))
def quarter_of(x, y):
for qnr, polys, (x0, x1, y0, y1) in quarters:
if x0 <= x <= x1 and y0 <= y <= y1:
for poly in polys:
if in_ring(x, y, poly[0]) and not any(in_ring(x, y, h) for h in poly[1:]):
return qnr
return None
archive = zipfile.ZipFile(io.BytesIO(fetch(ADDRESSES)))
name = next(n for n in archive.namelist() if n.endswith(".csv"))
counts = collections.defaultdict(collections.Counter)
outside = 0
with archive.open(name) as raw:
for row in csv.DictReader(io.TextIOWrapper(raw, encoding="utf-8-sig"), delimiter=";"):
if row["COM_FOSNR"] != CITY or row["ADR_STATUS"] != "real":
continue
qnr = quarter_of(float(row["ADR_EASTING"]), float(row["ADR_NORTHING"]))
if qnr is None:
outside += 1
continue
counts[row["ZIP_LABEL"].split()[0]][qnr] += 1
if outside:
print(f"{outside} addresses lie in no quarter", file=sys.stderr)
with open(OUT, "w", newline="", encoding="utf-8") as fh:
w = csv.writer(fh)
w.writerow(["postcode", "locality", "quarter", "share", "addresses"])
for postcode in sorted(counts):
total = sum(counts[postcode].values())
for qnr, n in sorted(counts[postcode].items(), key=lambda kv: (-kv[1], kv[0])):
w.writerow([postcode, "Zürich", qnr, f"{100 * n / total:.2f}", n])
print(f"{sum(len(c) for c in counts.values())} rows for {len(counts)} postcodes")
if __name__ == "__main__":
main()