# Install duckOSM when it is not installed (for example in Colab). It takes approximately 1 minute.# Until duckOSM 0.9.0 is on PyPI, the SDK of these notebooks is in the nightly wheel of main (the GitHub pre-release "nightly").# roadstyle (the maps) also comes from its nightly wheel, so the newest roadstyle parts work with no roadstyle release.import importlib.util, json, os, urllib.requestdef nightly_wheel(repo="Khoshkhah/duckOSM", name=".whl"): # the address of the newest nightly wheel of a repository release = json.load(urllib.request.urlopen(f"https://api.github.com/repos/{repo}/releases/tags/nightly"))returnnext(a["browser_download_url"] for a in release["assets"] if name in a["name"] and a["name"].endswith(".whl"))if importlib.util.find_spec("duckosm") isNone: # not installed: install it with the extras of this notebook%pip install -q "duckosm[viz] @ {nightly_wheel()}"%pip install -q --force-reinstall --no-deps "roadstyle @ {nightly_wheel('Khoshkhah/roadstyle', 'manylinux')}"import duckosm # the SDKifnothasattr(duckosm, "network"): # an old duckOSM (0.8.0 or older), without the SDK%pip install -q --force-reinstall --no-deps "duckosm @ {nightly_wheel()}"raiseSystemExit("duckOSM is updated: restart the session (in Colab: Runtime > Restart session), then run this cell again")print("duckosm", duckosm.__version__) # the version# The network of chapter 1 (monaco.duckdb). The chapter opens it. When you run this chapter alone (in Colab), the file# is not there, so this cell makes it one time.ifnot os.path.exists("monaco.duckdb") ornot duckosm.open("monaco.duckdb").has_mode("driving", "walking", "cycling"): duckosm.network(osm_id=2220322, modes=["driving", "walking", "cycling"], path="monaco.duckdb")
4.1 The goal of this chapter
You have data about roads from another source, for example a file of traffic counts from the city: one number for each road and each direction. You want this data on the duckOSM network, so that you can sort the roads by it, query it with SQL and color the map by it. At the end of the chapter you can:
give each row of your data its edge_id, the key of a duckOSM edge;
join your data to the edges in pandas or in SQL;
color the map and the dashboard by your data;
build the network again and find your data on the same roads.
4.2 Your data and the edges
Much data about roads has one value for each road and each direction: traffic counts, measured speeds, noise, the results of a model. To use it with a duckOSM network, each value needs the edge that it belongs to. The key of an edge is edge_id (chapter 2, “What edge_id is”).
Key
Stable after a new build?
Same in each mode?
Use it to join?
edge_id
yes: it comes from osm_id, source and target
yes
yes
edge_ref (4230114#3f)
no: the part number changes when the way gets more nodes
yes
no, only to read
the row number
no: another build or another filter gives another order
no
no
osm_id
yes
yes
no: one way has many edges, in two directions
the geometry
almost: a small change of a node moves it
yes
no: use map matching (chapter 11)
The flow of this chapter: you make the data once with edge_id in it, keep it in a file, and join it to the network each time that you need it. The join is the same in pandas, in SQL and on the map.
ImportantKey idea
Keep edge_id in your data, and join on it. The same edge_id is in each new build of the same OSM data and in each mode, so your data stays on the correct roads.
The counts in this chapter are made up. Real counts come from sensors: chapter 11 shows how to put GPS points and sensor data onto the edges.
4.3 Open the network of chapter 1
Chapter 1 builds Monaco with three modes (driving, walking and cycling) and saves it as monaco.duckdb. This chapter opens that file with duckosm.open: it builds nothing. The counts are on the driving network.
net = duckosm.open("monaco.duckdb")net
Network monaco
file
monaco.duckdb (37.0 MB)
OSM data
2026-11-18 (Geofabrik monaco)
fixes
none
saved
yes
mode
edges
nodes
km
oneway_km
driving
2840
1768
96.2
35.5
walking
11938
4589
260.6
0.0
cycling
11305
4650
250.0
35.5
4.4 Make the counts
In real work, a file from the city gives one count for each direction of the main roads. Here you make the counts yourself, in three steps:
Get the main roads: the primary, secondary and tertiary edges of the driving network.
Give each edge a base count by its road class: 900 vehicles per hour for a primary road, 500 for a secondary road and 250 for a tertiary road.
Multiply each base count by a random number from 0.5 to 1.5. The seed 1 gives the same numbers in each run.
The result is a table with two columns: edge_id and the count.
import numpy as npimport pandas as pdmain = net.driving.edges(where="highway IN ('primary', 'secondary', 'tertiary')")base = main.highway.map({"primary": 900, "secondary": 500, "tertiary": 250})
Each row is one edge: one direction of one part of a road. The table has 1013 rows, one for each primary, secondary and tertiary edge.
4.4.1 The type of edge_id
edge_id is a 64-bit integer, with up to 19 digits. A float64 keeps only approximately 16 digits, so a float changes most ids. The cell turns the ids into floats and back, and counts the ids that changed.
1007 of the 1013 ids changed: a join on them finds almost no edges. Only the 6 small ids stay the same.
WarningWarning
Keep edge_id as int64 (BIGINT in SQL). A float column, a spreadsheet program or a JSON reader that reads each number as a float changes the ids. pandas reads a CSV file of integers as int64, and Parquet keeps the type. In a spreadsheet, keep the column as text.
4.5 Join on edge_id
pandas.merge joins the counts to the edges. how="left" keeps all edges: an edge without a count gets NaN. Then you have all columns of the edge next to its count.
The five largest counts (1307 to 1324) are on primary roads, near the top of their range (900 × 1.5 = 1350): the Boulevard du Larvotto, the tunnels Pasteur and Albert II, and two edges without a name. gdf is still a GeoDataFrame: it has the geometry of each edge.
print(gdf.vehicles_per_hour.notna().sum(), "of", len(gdf), "edges have a count")gdf.groupby("highway").vehicles_per_hour.mean().dropna().round()
1013 of 2840 edges have a count
highway
primary 872.0
secondary 507.0
tertiary 253.0
Name: vehicles_per_hour, dtype: float64
1013 of the 2840 driving edges have a count. The mean count of each class is near its base: approximately 900, 500 and 250.
4.5.1 Join in SQL
The same join works in DuckDB. con.register gives your DataFrame a table name on the connection, so a query can join it to the tables of the file. DuckDB computes the join, and only the result comes to Python.
The query in the cell below:
joins the driving edges (driving.edges, the name e) to your counts (counts, the name c) on edge_id (USING (edge_id));
puts the rows in groups by road class (GROUP BY e.highway);
gives for each class the number of edges, the mean count, and the sum of count × length in km.
with net.connect() as con: con.register("counts", counts) by_class = con.sql(""" SELECT e.highway, count(*) AS edges, round(avg(c.vehicles_per_hour)) AS mean_vph, round(sum(c.vehicles_per_hour * e.length_m) / 1000) AS vehicle_km_per_hour FROM driving.edges e JOIN counts c USING (edge_id) GROUP BY e.highway ORDER BY mean_vph DESC """).df()by_class
highway
edges
mean_vph
vehicle_km_per_hour
0
primary
197
872.0
9886.0
1
secondary
429
507.0
7658.0
2
tertiary
387
253.0
3230.0
NoteWhat the output shows
197 primary, 429 secondary and 387 tertiary edges, with mean counts of 872, 507 and 253 vehicles per hour. vehicle_km_per_hour is the distance that all vehicles drive on the class in one hour: 9886 km on the primary roads.
4.5.2 Your data in a file
Keep your data in a Parquet file: it keeps edge_id as int64. net.sql can read a Parquet file in the query, so you do not need to read it into pandas first.
import osos.makedirs("out", exist_ok=True)counts.to_parquet("out/counts.parquet")net.sql(""" SELECT e.name, e.highway, c.vehicles_per_hour FROM driving.edges e JOIN 'out/counts.parquet' c USING (edge_id) WHERE e.name IS NOT NULL ORDER BY c.vehicles_per_hour DESC LIMIT 5""")
name
highway
vehicles_per_hour
0
Boulevard du Larvotto
primary
1312
1
Tunnel Pasteur
primary
1308
2
Tunnel Albert II
primary
1307
3
Boulevard du Larvotto
primary
1290
4
Tunnel Rainier III
primary
1287
The five largest counts on named roads, from 1287 to 1312 vehicles per hour. DuckDB reads the Parquet file with the path in the query. The path is from the folder of the notebook.
4.6 Color the map by the counts
color_by takes your own data keyed by edge_id (chapter 3, “Color the roads by a column”). A Series with edge_id as its index is the short form. The edges without a count are gray. Run the cell to see the live map: you can zoom, and click a road to see its columns. This page shows the static picture of the map.
The color bar is the count in vehicles per hour. The dark lines are the primary roads with the largest counts. The thin gray lines are the edges without a count: the residential streets and the service roads.
4.6.1 Show only some edges: highlight
color_by also takes a DataFrame with edge_id and one value column (color_by=counts gives the same map), or the name of a column of the edges. To show only some edges, give their ids to highlight. The cell shows the edges with more than 1000 vehicles per hour.
65 edges are busy, all on primary roads, because only a primary road can have more than 1000 vehicles per hour here (500 × 1.5 = 750 is the maximum of a secondary road).
4.6.2 Save the map
save_map writes the same map as one HTML file, with the same options (chapter 3, “Save a map as a file”). Send the file to a person who has no Python.
A map shows the pattern of your data: where the counts are high and where they are low. A dashboard also lets you look at one road. It is the same colored map, with a panel at its left. When you click a road, the panel shows the card of the road: its OSM data and the value of your data for it.
net.dashboard() takes the same color_by and cmap as net.map(). The cell below gives the dashboard of the counts.
On this page the output is a picture, so you cannot click it. In your notebook the dashboard is live. The picture below shows it after a click on Boulevard du Larvotto:
The dashboard of the counts: the colored map, and the card of Boulevard du Larvotto in the panel, with vehicles_per_hour 1151
The table names each part of the picture.
Part
What it shows
the map
each counted road in the color of its count: light for a low count, dark for a high count. The gray roads have no count
the card in the panel
the road that you clicked: its name, edge_id, osm_id, road class, lanes, speed limit and your column vehicles_per_hour (1151 for this road)
the small box on the map
a short form of the card, at the clicked road
the buttons at the right
zoom, 3D, the base map layers and the buildings
To use it:
Run the cell.
Click a road on the map.
Read its count in the card. Click another road to compare.
Use
When
net.map(color_by=...)
you want to see the pattern of the data over the area
net.dashboard(color_by=...)
you also want to look at single roads and read their values
To keep the dashboard as a file that opens in any browser, use net.save_map("counts.html", dashboard=True, color_by=by_edge, cmap="magma_r").
4.8 The same data in more modes
A street with a sidewalk has the same edge_id in the driving and in the walking network. So counts that you join to the driving network are also on the walking network, without a second join key. The walking network is in the same file, monaco.duckdb.
on_walk = counts.edge_id.isin(net.walking.edges().edge_id)print(on_walk.sum(), "of", len(counts), "counted edges are also walking edges")
612 of 1013 counted edges are also walking edges
NoteWhat the output shows
612 of the 1013 counted edges are also in the walking network: the main roads with a sidewalk. The other 401 edges have no walking twin. 55 of them are in tunnels, where walking is not allowed. On others, OSM can draw the sidewalk as a separate way: then the walking network uses that way, not the road.
4.9 The ids stay after a rebuild
Build Monaco again into a new file. The same counts join to the same edges, with no change.
again = duckosm.network(osm_id=2220322, modes=["driving"], name="monaco_again")counts.edge_id.isin(again.driving.edges().edge_id).all()
True: each of the 1013 counts finds its edge in the new file. When the OSM data changes (a new extract, or a fix of chapter 5), only the edges of the changed ways get new ids. Chapter 5 shows how to list them with net.diff, and chapter 11 shows duckosm.mobility.edge_id_map, which connects old ids to new ids.
TipTip
To move data from an old build to a new build of other OSM data, join on edge_id first. Only the rows that find no edge need more work.
4.10 Try it yourself
1. Give each driving edge a made-up speed (for example maxspeed_kmh times a random number from 0.6 to 1.0) and draw the map of the speeds.
2. Write the counts to a CSV file, read it again with pandas, and check that the ids are the same.
TipShow the answer
counts.to_csv("out/counts.csv", index=False)import pandas as pdback = pd.read_csv("out/counts.csv")back.edge_id.dtype, back.edge_id.equals(counts.edge_id)
3. Find the sum of the counts on each named road, with SQL on the Parquet file.
TipShow the answer
net.sql("""SELECT e.name, sum(c.vehicles_per_hour) AS vph FROM driving.edges e JOIN 'out/counts.parquet' c USING (edge_id) WHERE e.name IS NOT NULL GROUP BY e.name ORDER BY vph DESC LIMIT 10""")
4.11 Words in this chapter
Word
Meaning
join
putting two tables together on a key column
key
the column that tells which rows belong together: here edge_id
left join
a join that keeps all rows of the first table. A row without a match gets NULL or NaN
int64, BIGINT
a 64-bit integer: the type of edge_id in pandas and in DuckDB
Parquet
a column file format that keeps the types of the columns
register
a DuckDB call that gives a DataFrame a table name on a connection
vehicles per hour
the number of vehicles that pass one point of a road in one hour
4.12 Summary
Call
Does
net.driving.edges(where=...)
the edges of one mode, filtered in SQL
edges.merge(data, on="edge_id", how="left")
your data on the edges, in pandas
con.register("name", df) in net.connect()
your DataFrame as a table in SQL
net.sql("... JOIN 'file.parquet' USING (edge_id)")
your data from a Parquet file, joined in SQL
net.map(color_by=series, cmap=...)
a map colored by your data
net.map(highlight=ids)
some edges in orange
net.dashboard(color_by=series, cmap=...)
the dashboard colored by your data, with the value in the road card
net.save_map(path, color_by=...)
the map of your data as one HTML file
counts.edge_id.isin(other.edges().edge_id)
check that your data finds its edges in another file