|
| 1 | +# Group records by place |
| 2 | + |
| 3 | +A Nigerian postcode says where a building is at five levels: state, LGA, district, area, and building. Cut a code off after one of those and you have a prefix that every building in that place shares. Counting customers, deliveries, or cases by district is then an ordinary group-by, with no map and no boundary files. |
| 4 | + |
| 5 | +| Cut after | Prefix of `EK-01-A03-FK-01` | |
| 6 | +| --- | --- | |
| 7 | +| State | `EK` | |
| 8 | +| LGA | `EK-01` | |
| 9 | +| District | `EK-01-A03` | |
| 10 | +| Area | `EK-01-A03-FK` | |
| 11 | + |
| 12 | +## In Python |
| 13 | + |
| 14 | +```python |
| 15 | +from collections import Counter |
| 16 | + |
| 17 | +from ng_postcode import Postcode, Segment, parse |
| 18 | + |
| 19 | + |
| 20 | +def district(text: str) -> str | None: |
| 21 | + """The district a code is in, or None for one that is not well formed.""" |
| 22 | + code = parse(text) |
| 23 | + return str(code.truncate(Segment.DISTRICT)) if isinstance(code, Postcode) else None |
| 24 | + |
| 25 | + |
| 26 | +rows = ["EK-01-A03-FK-01", "ek 01 a03 zz 14", "LA11W06TC10", "not a code"] |
| 27 | +print(Counter(map(district, rows))) |
| 28 | +# Counter({'EK-01-A03': 2, 'LA-11-W06': 1, None: 1}) |
| 29 | +``` |
| 30 | + |
| 31 | +The same function works on a column: |
| 32 | + |
| 33 | +```python |
| 34 | +frame["postcode"].map(district).value_counts(dropna=False) # pandas |
| 35 | +table.group_by(pl.col("postcode").map_elements(district, return_dtype=pl.String)).len() # Polars |
| 36 | +``` |
| 37 | + |
| 38 | +Rows that are not well-formed codes come out under `None`, so they are counted and visible. |
| 39 | + |
| 40 | +## In SQL |
| 41 | + |
| 42 | +```sql |
| 43 | +SELECT ng_postcode_format(ng_postcode_truncate(postcode, 'district')) AS district, count(*) |
| 44 | +FROM customers |
| 45 | +GROUP BY 1; |
| 46 | +``` |
| 47 | + |
| 48 | +The functions for PostgreSQL and DuckDB are in [`sql/`](https://github.com/Adeniyikayodee/ng-postcode/tree/main/sql). |
| 49 | + |
| 50 | +## What a prefix does not tell you |
| 51 | + |
| 52 | +A prefix groups buildings that NIPOST placed in the same district or area. It carries no name, boundary, or population. Names come from NIPOST's lookup, and a well-formed code is not necessarily assigned to a building. |
0 commit comments