Skip to content

Data Structures

API Description
TrajDataFrame Narwhals-backed wrapper for trajectory data.
FlowDataFrame Narwhals-backed wrapper for origin-destination flow data.

TrajDataFrame

fastmob.core.TrajDataFrame

Bases: BaseDataFrame

Narwhals-backed wrapper for trajectory data.

Accepts any eager DataFrame backend (pandas, polars, …) and exposes a unified mobility-analysis API. Column names are auto-detected from a priority list; custom names can be supplied explicitly.

Parameters:

Name Type Description Default
df DataFrame - like

Source data. Accepted types: pandas.DataFrame, polars.DataFrame, any Narwhals-compatible eager frame, plain list, numpy.ndarray, or dict.

required
sort bool

If True, sort the underlying data by (uid, datetime) on construction. Default False.

False
timestamp bool

If True, parse the datetime column from Unix timestamps. Default False.

False
datetime_col str

Name of the datetime column in df (overrides auto-detection).

None
lat_col str

Name of the latitude column (overrides auto-detection).

None
lng_col str

Name of the longitude column (overrides auto-detection).

None
uid_col str

Name of the user-ID column (overrides auto-detection).

None
latitude str

Source column to rename to 'lat'.

None
longitude str

Source column to rename to 'lng'.

None
datetime str

Source column to rename to 'datetime'.

None
user_id str

Source column to rename to 'uid'.

None
trajectory_id str

Source column to rename to 'tid'.

None
crs dict

Coordinate reference system. Default {"init": "epsg:4326"}.

None
parameters dict

Arbitrary metadata dictionary. Default {}.

None

Examples:

>>> import pandas as pd
>>> import fastmob
>>> data = [
...     [1, 39.984094, 116.319236, "2008-10-23 13:53:05"],
...     [1, 39.984198, 116.319322, "2008-10-23 13:53:06"],
...     [1, 39.984224, 116.319402, "2008-10-23 13:53:11"],
... ]
>>> df = pd.DataFrame(data, columns=["uid", "lat", "lng", "datetime"])
>>> tdf = fastmob.TrajDataFrame(df)
>>> tdf.uid_col
'uid'

common_part_of_commuters(other, resolution=9)

Compute trajectory CPC against another trajectory at an H3 resolution.

compress(spatial_radius_km=0.2, inplace=False)

Compress the trajectory by collapsing nearby consecutive points.

Parameters:

Name Type Description Default
spatial_radius_km float

Spatial radius (km) used to decide whether two consecutive points belong to the same stop. Default 0.2.

0.2
inplace bool

If True, modify this object and return self. If False (default), return a new TrajDataFrame.

False

Returns:

Type Description
TrajDataFrame

Examples:

>>> import pandas as pd
>>> import fastmob
>>> df = pd.DataFrame({
...     "uid": [1, 1, 1],
...     "lat": [0.0, 0.0001, 1.0],
...     "lng": [0.0, 0.0001, 0.0],
...     "datetime": pd.date_range("2020-01-01", periods=3, freq="h"),
... })
>>> tdf = fastmob.TrajDataFrame(df)
>>> tdf.compress()

jump_lengths(merge=False)

Compute the jump lengths (km) between consecutive GPS points.

Parameters:

Name Type Description Default
merge bool

If True, merge the result back onto the original DataFrame. Default False.

False

Returns:

Type Description
DataFrame

A DataFrame with columns uid (when a user column is present) and jump_lengths containing a list of distances per user.

Examples:

>>> import pandas as pd
>>> import fastmob
>>> df = pd.DataFrame({
...     "uid": [1, 1, 1],
...     "lat": [0.0, 1.0, 2.0],
...     "lng": [0.0, 0.0, 0.0],
...     "datetime": pd.date_range("2020-01-01", periods=3, freq="h"),
... })
>>> tdf = fastmob.TrajDataFrame(df)
>>> tdf.jump_lengths()

mapping(tessellation, remove_na=False)

Assign each trajectory point to a tile in a spatial tessellation.

Adds a tile_id column to the result.

Parameters:

Name Type Description Default
tessellation GeoDataFrame

Spatial tessellation with Polygon or Point geometries and a tile_id column.

required
remove_na bool

If True, remove points that fall outside the tessellation. Default False (keep them with NaN tile_id).

False

Returns:

Type Description
TrajDataFrame

Original trajectory with an extra tile_id column.

Notes

Requires fastmob[data]::

pip install "fastmob[data]"

Examples:

>>> import fastmob
>>> tdf = fastmob.data.load_dataset("foursquare_nyc")
>>> from fastmob.tessellation.tilers import tiler
>>> tess = tiler.get("squared", base_shape="New York City", meters=2000)
>>> mapped = tdf.mapping(tess)

plot_diary(user, start_datetime=None, end_datetime=None, ax=None, legend=False)

Plot a mobility diary for a single user as a coloured time-span chart.

Requires a clustered stop DataFrame (output of fastmob.preprocessing.cluster), with cluster and leaving_datetime columns.

Parameters:

Name Type Description Default
user str or int

Identifier of the user to plot.

required
start_datetime datetime

Only stops after this datetime are included. Defaults to the earliest stop.

None
end_datetime datetime

Only stops before this datetime are included. Defaults to the latest departure.

None
ax Axes

Axes to draw on. A new figure is created if None.

None
legend bool

Show a cluster-ID legend. Default False.

False

Returns:

Type Description
Axes
Notes

Requires fastmob[visualization]::

pip install "fastmob[visualization]"

Examples:

>>> import fastmob
>>> tdf = fastmob.data.load_dataset("foursquare_nyc")
>>> stdf = tdf.stay_locations(minutes_for_a_stop=20)
>>> cstdf = fastmob.preprocessing.cluster(stdf)
>>> ax = cstdf.plot_diary(user=1)

plot_stops(map_f=None, max_users=None, tiles='cartodbpositron', zoom=12, hex_color=None, opacity=0.3, radius=12, number_of_sides=4, popup=True, control_scale=True)

Plot detected stop locations on an interactive Folium map.

Requires a TrajDataFrame with a leaving_datetime column (output of :func:fastmob.preprocessing.stay_locations).

Parameters:

Name Type Description Default
map_f Map

Existing map. Creates a new map if None.

None
max_users int

Maximum number of users to plot. Defaults to 10 with a warning.

None
tiles str

Folium tile layer. Default 'cartodbpositron'.

'cartodbpositron'
zoom int

Initial zoom. Default 12.

12
hex_color str

Fixed hex color. Random color per user if None.

None
opacity float

Marker fill opacity. Default 0.3.

0.3
radius float

Marker radius. Default 12.

12
number_of_sides int

Number of polygon sides for each marker. Default 4.

4
popup bool

Show an info popup on click. Default True.

True
control_scale bool

Add a scale bar. Default True.

True

Returns:

Type Description
Map
Notes

Requires fastmob[visualization]::

pip install "fastmob[visualization]"

Examples:

>>> import fastmob
>>> tdf = fastmob.data.load_dataset("foursquare_nyc")
>>> stdf = tdf.stay_locations(minutes_for_a_stop=20)
>>> m = stdf.plot_stops(zoom=12)

plot_trajectory(map_f=None, max_users=None, max_points=1000, style_function=None, tiles='cartodbpositron', zoom=12, hex_color=None, weight=2, opacity=0.75, dashArray='0, 0', start_end_markers=True, control_scale=True)

Plot trajectories on an interactive Folium map.

Parameters:

Name Type Description Default
map_f Map

Existing map to draw on. Creates a new map if None.

None
max_users int

Maximum number of users to plot. Defaults to 10 with a warning.

None
max_points int

Maximum GPS points per user. Trajectories are down-sampled if longer. Default 1000.

1000
style_function callable

GeoJson style factory (weight, color, opacity, dashArray) → fn. Defaults to fastmob.utils.plot.traj_style_function.

None
tiles str

Folium tile layer name. Default 'cartodbpositron'.

'cartodbpositron'
zoom int

Initial zoom level. Default 12.

12
hex_color str

Fixed hex color for all lines. Random color per user if None.

None
weight float

Line thickness. Default 2.

2
opacity float

Line opacity. Default 0.75.

0.75
dashArray str

SVG dash pattern, e.g. '5, 5'. Default '0, 0' (solid).

'0, 0'
start_end_markers bool

Add green/red markers at start and end. Default True.

True
control_scale bool

Add a map scale bar. Default True.

True

Returns:

Type Description
Map
Notes

Requires fastmob[visualization]::

pip install "fastmob[visualization]"

Examples:

>>> import fastmob
>>> tdf = fastmob.data.load_dataset("foursquare_nyc")
>>> m = tdf.plot_trajectory(zoom=12)

radius_of_gyration()

Compute the radius of gyration (km) for each user.

Returns:

Type Description
DataFrame

A DataFrame with columns uid (when present) and radius_of_gyration.

Examples:

>>> import pandas as pd
>>> import fastmob
>>> df = pd.DataFrame({
...     "uid": [1, 1, 1],
...     "lat": [0.0, 1.0, 2.0],
...     "lng": [0.0, 0.0, 0.0],
...     "datetime": pd.date_range("2020-01-01", periods=3, freq="h"),
... })
>>> tdf = fastmob.TrajDataFrame(df)
>>> tdf.radius_of_gyration()

settings_from(other)

Copy metadata attributes from another TrajDataFrame.

Parameters:

Name Type Description Default
other TrajDataFrame

Source TrajDataFrame to copy attributes from.

required

Examples:

>>> import pandas as pd
>>> import fastmob
>>> df = pd.DataFrame({
...     "uid": [1], "lat": [0.0], "lng": [0.0],
...     "datetime": pd.date_range("2020-01-01", periods=1),
... })
>>> tdf1 = fastmob.TrajDataFrame(df.copy())
>>> tdf2 = fastmob.TrajDataFrame(df.copy(), parameters={"source": "gps"})
>>> tdf1.settings_from(tdf2)
>>> tdf1.parameters
{'source': 'gps'}

sort_by_uid_and_datetime()

Return a copy sorted by user ID then datetime.

Returns:

Type Description
TrajDataFrame

New TrajDataFrame with rows sorted ascending by (uid, datetime).

Examples:

>>> import pandas as pd
>>> import fastmob
>>> df = pd.DataFrame({
...     "uid": [2, 1, 1],
...     "lat": [0.0, 1.0, 2.0],
...     "lng": [0.0, 0.0, 0.0],
...     "datetime": pd.date_range("2020-01-01", periods=3, freq="h"),
... })
>>> tdf = fastmob.TrajDataFrame(df)
>>> sorted_tdf = tdf.sort_by_uid_and_datetime()

stay_locations(inplace=False, **kwargs)

Detect stay locations (stops) in the trajectory.

Parameters:

Name Type Description Default
inplace bool

If True, modify this object and return self. If False (default), return a new TrajDataFrame.

False
**kwargs

Extra keyword arguments forwarded to fastmob.preprocessing.stay_locations.

{}

Returns:

Type Description
TrajDataFrame

A DataFrame whose rows are detected stops, with an extra leaving_datetime column.

Examples:

>>> import pandas as pd
>>> import fastmob
>>> df = pd.DataFrame({
...     "uid": [1, 1, 1, 1],
...     "lat": [0.0, 0.0001, 0.0, 1.0],
...     "lng": [0.0, 0.0, 0.0001, 0.0],
...     "datetime": pd.date_range("2020-01-01", periods=4, freq="30min"),
... })
>>> tdf = fastmob.TrajDataFrame(df)
>>> tdf.stay_locations(minutes_for_a_stop=20)

timezone_conversion(from_timezone, to_timezone)

Convert the datetime column from one timezone to another, in place.

The result has timezone information stripped (tz-naive), matching the behaviour of the original scikit-mobility implementation.

Parameters:

Name Type Description Default
from_timezone str

Current timezone of the datetime column, e.g. 'GMT'.

required
to_timezone str

Target timezone, e.g. 'Asia/Shanghai'.

required

Examples:

>>> import pandas as pd
>>> import fastmob
>>> df = pd.DataFrame({
...     "uid": [1, 1],
...     "lat": [39.984, 39.985],
...     "lng": [116.319, 116.320],
...     "datetime": pd.to_datetime(["2008-10-23 05:53:05", "2008-10-23 05:53:06"]),
... })
>>> tdf = fastmob.TrajDataFrame(df)
>>> tdf.timezone_conversion("GMT", "Asia/Shanghai")
>>> tdf[tdf.datetime_col].iloc[0]
Timestamp('2008-10-23 13:53:05')

to_flowdataframe(tessellation, self_loops=True)

Aggregate the trajectory into a FlowDataFrame using a tessellation.

Points outside the tessellation are silently dropped.

Parameters:

Name Type Description Default
tessellation GeoDataFrame

Spatial tessellation with a tile_id column and polygon geometries.

required
self_loops bool

If True (default), include movements that start and end in the same tile.

True

Returns:

Type Description
FlowDataFrame
Notes

Requires fastmob[data]::

pip install "fastmob[data]"

Examples:

>>> import fastmob
>>> tdf = fastmob.data.load_dataset("foursquare_nyc")
>>> from fastmob.tessellation.tilers import tiler
>>> tess = tiler.get("squared", base_shape="New York City", meters=2000)
>>> fdf = tdf.to_flowdataframe(tess)

to_geodataframe()

Convert to a geopandas.GeoDataFrame with Point geometry.

Returns:

Type Description
GeoDataFrame

Same rows as the trajectory, with an additional geometry column containing shapely.geometry.Point objects built from the latitude and longitude columns.

Notes

Requires fastmob[data]::

pip install "fastmob[data]"

Examples:

>>> import pandas as pd
>>> import fastmob
>>> df = pd.DataFrame({
...     "uid": [1, 1],
...     "lat": [48.8566, 48.8578],
...     "lng": [2.3522, 2.3530],
...     "datetime": pd.date_range("2020-01-01", periods=2, freq="h"),
... })
>>> tdf = fastmob.TrajDataFrame(df)
>>> gdf = tdf.to_geodataframe()

Measure methods

API Description
TrajDataFrame.jump_lengths Compute jump lengths (km) between consecutive GPS points.
TrajDataFrame.radius_of_gyration Compute the radius of gyration (km) for each user.

fastmob.core.trajectory_dataframe.TrajDataFrame.jump_lengths(merge=False)

Compute the jump lengths (km) between consecutive GPS points.

Parameters:

Name Type Description Default
merge bool

If True, merge the result back onto the original DataFrame. Default False.

False

Returns:

Type Description
DataFrame

A DataFrame with columns uid (when a user column is present) and jump_lengths containing a list of distances per user.

Examples:

>>> import pandas as pd
>>> import fastmob
>>> df = pd.DataFrame({
...     "uid": [1, 1, 1],
...     "lat": [0.0, 1.0, 2.0],
...     "lng": [0.0, 0.0, 0.0],
...     "datetime": pd.date_range("2020-01-01", periods=3, freq="h"),
... })
>>> tdf = fastmob.TrajDataFrame(df)
>>> tdf.jump_lengths()

fastmob.core.trajectory_dataframe.TrajDataFrame.radius_of_gyration()

Compute the radius of gyration (km) for each user.

Returns:

Type Description
DataFrame

A DataFrame with columns uid (when present) and radius_of_gyration.

Examples:

>>> import pandas as pd
>>> import fastmob
>>> df = pd.DataFrame({
...     "uid": [1, 1, 1],
...     "lat": [0.0, 1.0, 2.0],
...     "lng": [0.0, 0.0, 0.0],
...     "datetime": pd.date_range("2020-01-01", periods=3, freq="h"),
... })
>>> tdf = fastmob.TrajDataFrame(df)
>>> tdf.radius_of_gyration()

Preprocessing methods

API Description
TrajDataFrame.compress Compress the trajectory by collapsing nearby consecutive points.
TrajDataFrame.stay_locations Detect stay locations (stops) in the trajectory.

fastmob.core.trajectory_dataframe.TrajDataFrame.compress(spatial_radius_km=0.2, inplace=False)

Compress the trajectory by collapsing nearby consecutive points.

Parameters:

Name Type Description Default
spatial_radius_km float

Spatial radius (km) used to decide whether two consecutive points belong to the same stop. Default 0.2.

0.2
inplace bool

If True, modify this object and return self. If False (default), return a new TrajDataFrame.

False

Returns:

Type Description
TrajDataFrame

Examples:

>>> import pandas as pd
>>> import fastmob
>>> df = pd.DataFrame({
...     "uid": [1, 1, 1],
...     "lat": [0.0, 0.0001, 1.0],
...     "lng": [0.0, 0.0001, 0.0],
...     "datetime": pd.date_range("2020-01-01", periods=3, freq="h"),
... })
>>> tdf = fastmob.TrajDataFrame(df)
>>> tdf.compress()

fastmob.core.trajectory_dataframe.TrajDataFrame.stay_locations(inplace=False, **kwargs)

Detect stay locations (stops) in the trajectory.

Parameters:

Name Type Description Default
inplace bool

If True, modify this object and return self. If False (default), return a new TrajDataFrame.

False
**kwargs

Extra keyword arguments forwarded to fastmob.preprocessing.stay_locations.

{}

Returns:

Type Description
TrajDataFrame

A DataFrame whose rows are detected stops, with an extra leaving_datetime column.

Examples:

>>> import pandas as pd
>>> import fastmob
>>> df = pd.DataFrame({
...     "uid": [1, 1, 1, 1],
...     "lat": [0.0, 0.0001, 0.0, 1.0],
...     "lng": [0.0, 0.0, 0.0001, 0.0],
...     "datetime": pd.date_range("2020-01-01", periods=4, freq="30min"),
... })
>>> tdf = fastmob.TrajDataFrame(df)
>>> tdf.stay_locations(minutes_for_a_stop=20)

Conversion methods

API Description
TrajDataFrame.to_flowdataframe Aggregate trajectory into a FlowDataFrame using a tessellation. Requires fastmob[data].
TrajDataFrame.to_geodataframe Convert to a geopandas.GeoDataFrame with Point geometry. Requires fastmob[data].
TrajDataFrame.mapping Assign each point to a tessellation tile. Requires fastmob[data].

fastmob.core.trajectory_dataframe.TrajDataFrame.to_flowdataframe(tessellation, self_loops=True)

Aggregate the trajectory into a FlowDataFrame using a tessellation.

Points outside the tessellation are silently dropped.

Parameters:

Name Type Description Default
tessellation GeoDataFrame

Spatial tessellation with a tile_id column and polygon geometries.

required
self_loops bool

If True (default), include movements that start and end in the same tile.

True

Returns:

Type Description
FlowDataFrame
Notes

Requires fastmob[data]::

pip install "fastmob[data]"

Examples:

>>> import fastmob
>>> tdf = fastmob.data.load_dataset("foursquare_nyc")
>>> from fastmob.tessellation.tilers import tiler
>>> tess = tiler.get("squared", base_shape="New York City", meters=2000)
>>> fdf = tdf.to_flowdataframe(tess)

fastmob.core.trajectory_dataframe.TrajDataFrame.to_geodataframe()

Convert to a geopandas.GeoDataFrame with Point geometry.

Returns:

Type Description
GeoDataFrame

Same rows as the trajectory, with an additional geometry column containing shapely.geometry.Point objects built from the latitude and longitude columns.

Notes

Requires fastmob[data]::

pip install "fastmob[data]"

Examples:

>>> import pandas as pd
>>> import fastmob
>>> df = pd.DataFrame({
...     "uid": [1, 1],
...     "lat": [48.8566, 48.8578],
...     "lng": [2.3522, 2.3530],
...     "datetime": pd.date_range("2020-01-01", periods=2, freq="h"),
... })
>>> tdf = fastmob.TrajDataFrame(df)
>>> gdf = tdf.to_geodataframe()

fastmob.core.trajectory_dataframe.TrajDataFrame.mapping(tessellation, remove_na=False)

Assign each trajectory point to a tile in a spatial tessellation.

Adds a tile_id column to the result.

Parameters:

Name Type Description Default
tessellation GeoDataFrame

Spatial tessellation with Polygon or Point geometries and a tile_id column.

required
remove_na bool

If True, remove points that fall outside the tessellation. Default False (keep them with NaN tile_id).

False

Returns:

Type Description
TrajDataFrame

Original trajectory with an extra tile_id column.

Notes

Requires fastmob[data]::

pip install "fastmob[data]"

Examples:

>>> import fastmob
>>> tdf = fastmob.data.load_dataset("foursquare_nyc")
>>> from fastmob.tessellation.tilers import tiler
>>> tess = tiler.get("squared", base_shape="New York City", meters=2000)
>>> mapped = tdf.mapping(tess)

Utility methods

API Description
TrajDataFrame.sort_by_uid_and_datetime Return a copy sorted by user ID then datetime.
TrajDataFrame.settings_from Copy metadata attributes from another TrajDataFrame.
TrajDataFrame.timezone_conversion Convert the datetime column from one timezone to another, in place.

fastmob.core.trajectory_dataframe.TrajDataFrame.sort_by_uid_and_datetime()

Return a copy sorted by user ID then datetime.

Returns:

Type Description
TrajDataFrame

New TrajDataFrame with rows sorted ascending by (uid, datetime).

Examples:

>>> import pandas as pd
>>> import fastmob
>>> df = pd.DataFrame({
...     "uid": [2, 1, 1],
...     "lat": [0.0, 1.0, 2.0],
...     "lng": [0.0, 0.0, 0.0],
...     "datetime": pd.date_range("2020-01-01", periods=3, freq="h"),
... })
>>> tdf = fastmob.TrajDataFrame(df)
>>> sorted_tdf = tdf.sort_by_uid_and_datetime()

fastmob.core.trajectory_dataframe.TrajDataFrame.settings_from(other)

Copy metadata attributes from another TrajDataFrame.

Parameters:

Name Type Description Default
other TrajDataFrame

Source TrajDataFrame to copy attributes from.

required

Examples:

>>> import pandas as pd
>>> import fastmob
>>> df = pd.DataFrame({
...     "uid": [1], "lat": [0.0], "lng": [0.0],
...     "datetime": pd.date_range("2020-01-01", periods=1),
... })
>>> tdf1 = fastmob.TrajDataFrame(df.copy())
>>> tdf2 = fastmob.TrajDataFrame(df.copy(), parameters={"source": "gps"})
>>> tdf1.settings_from(tdf2)
>>> tdf1.parameters
{'source': 'gps'}

fastmob.core.trajectory_dataframe.TrajDataFrame.timezone_conversion(from_timezone, to_timezone)

Convert the datetime column from one timezone to another, in place.

The result has timezone information stripped (tz-naive), matching the behaviour of the original scikit-mobility implementation.

Parameters:

Name Type Description Default
from_timezone str

Current timezone of the datetime column, e.g. 'GMT'.

required
to_timezone str

Target timezone, e.g. 'Asia/Shanghai'.

required

Examples:

>>> import pandas as pd
>>> import fastmob
>>> df = pd.DataFrame({
...     "uid": [1, 1],
...     "lat": [39.984, 39.985],
...     "lng": [116.319, 116.320],
...     "datetime": pd.to_datetime(["2008-10-23 05:53:05", "2008-10-23 05:53:06"]),
... })
>>> tdf = fastmob.TrajDataFrame(df)
>>> tdf.timezone_conversion("GMT", "Asia/Shanghai")
>>> tdf[tdf.datetime_col].iloc[0]
Timestamp('2008-10-23 13:53:05')

Visualization methods

Visualization methods require the optional visualization extra:

pip install "fastmob[visualization]"
API Description
TrajDataFrame.plot_trajectory Plot trajectories on an interactive Folium map.
TrajDataFrame.plot_stops Plot detected stop locations on an interactive Folium map.
TrajDataFrame.plot_diary Plot a mobility diary as a coloured time-span chart.

fastmob.core.trajectory_dataframe.TrajDataFrame.plot_trajectory(map_f=None, max_users=None, max_points=1000, style_function=None, tiles='cartodbpositron', zoom=12, hex_color=None, weight=2, opacity=0.75, dashArray='0, 0', start_end_markers=True, control_scale=True)

Plot trajectories on an interactive Folium map.

Parameters:

Name Type Description Default
map_f Map

Existing map to draw on. Creates a new map if None.

None
max_users int

Maximum number of users to plot. Defaults to 10 with a warning.

None
max_points int

Maximum GPS points per user. Trajectories are down-sampled if longer. Default 1000.

1000
style_function callable

GeoJson style factory (weight, color, opacity, dashArray) → fn. Defaults to fastmob.utils.plot.traj_style_function.

None
tiles str

Folium tile layer name. Default 'cartodbpositron'.

'cartodbpositron'
zoom int

Initial zoom level. Default 12.

12
hex_color str

Fixed hex color for all lines. Random color per user if None.

None
weight float

Line thickness. Default 2.

2
opacity float

Line opacity. Default 0.75.

0.75
dashArray str

SVG dash pattern, e.g. '5, 5'. Default '0, 0' (solid).

'0, 0'
start_end_markers bool

Add green/red markers at start and end. Default True.

True
control_scale bool

Add a map scale bar. Default True.

True

Returns:

Type Description
Map
Notes

Requires fastmob[visualization]::

pip install "fastmob[visualization]"

Examples:

>>> import fastmob
>>> tdf = fastmob.data.load_dataset("foursquare_nyc")
>>> m = tdf.plot_trajectory(zoom=12)

fastmob.core.trajectory_dataframe.TrajDataFrame.plot_stops(map_f=None, max_users=None, tiles='cartodbpositron', zoom=12, hex_color=None, opacity=0.3, radius=12, number_of_sides=4, popup=True, control_scale=True)

Plot detected stop locations on an interactive Folium map.

Requires a TrajDataFrame with a leaving_datetime column (output of :func:fastmob.preprocessing.stay_locations).

Parameters:

Name Type Description Default
map_f Map

Existing map. Creates a new map if None.

None
max_users int

Maximum number of users to plot. Defaults to 10 with a warning.

None
tiles str

Folium tile layer. Default 'cartodbpositron'.

'cartodbpositron'
zoom int

Initial zoom. Default 12.

12
hex_color str

Fixed hex color. Random color per user if None.

None
opacity float

Marker fill opacity. Default 0.3.

0.3
radius float

Marker radius. Default 12.

12
number_of_sides int

Number of polygon sides for each marker. Default 4.

4
popup bool

Show an info popup on click. Default True.

True
control_scale bool

Add a scale bar. Default True.

True

Returns:

Type Description
Map
Notes

Requires fastmob[visualization]::

pip install "fastmob[visualization]"

Examples:

>>> import fastmob
>>> tdf = fastmob.data.load_dataset("foursquare_nyc")
>>> stdf = tdf.stay_locations(minutes_for_a_stop=20)
>>> m = stdf.plot_stops(zoom=12)

fastmob.core.trajectory_dataframe.TrajDataFrame.plot_diary(user, start_datetime=None, end_datetime=None, ax=None, legend=False)

Plot a mobility diary for a single user as a coloured time-span chart.

Requires a clustered stop DataFrame (output of fastmob.preprocessing.cluster), with cluster and leaving_datetime columns.

Parameters:

Name Type Description Default
user str or int

Identifier of the user to plot.

required
start_datetime datetime

Only stops after this datetime are included. Defaults to the earliest stop.

None
end_datetime datetime

Only stops before this datetime are included. Defaults to the latest departure.

None
ax Axes

Axes to draw on. A new figure is created if None.

None
legend bool

Show a cluster-ID legend. Default False.

False

Returns:

Type Description
Axes
Notes

Requires fastmob[visualization]::

pip install "fastmob[visualization]"

Examples:

>>> import fastmob
>>> tdf = fastmob.data.load_dataset("foursquare_nyc")
>>> stdf = tdf.stay_locations(minutes_for_a_stop=20)
>>> cstdf = fastmob.preprocessing.cluster(stdf)
>>> ax = cstdf.plot_diary(user=1)

FlowDataFrame

fastmob.core.FlowDataFrame

Bases: BaseDataFrame

Narwhals-backed wrapper for origin-destination flow data.

Stores a flow table with columns origin, destination, and flow, optionally coupled with a spatial tessellation (geopandas.GeoDataFrame).

Parameters:

Name Type Description Default
df DataFrame - like

Source data. Accepted types: pandas.DataFrame, polars.DataFrame, any Narwhals-compatible eager frame, list, numpy.ndarray, or dict.

None
origin str

Column name for origin tile IDs. Default 'origin'.

ORIGIN
destination str

Column name for destination tile IDs. Default 'destination'.

DESTINATION
flow str

Column name for flow values. Default 'flow'.

FLOW
tile_id str

Column name for tile IDs in the tessellation. Default 'tile_id'.

TILE_ID
tessellation GeoDataFrame

Spatial tessellation associated with the flow data.

None
parameters dict

Arbitrary metadata dictionary. Default {}.

None

Examples:

>>> import pandas as pd
>>> import fastmob
>>> flows = pd.DataFrame({
...     "origin": ["A", "A", "B"],
...     "destination": ["A", "B", "A"],
...     "flow": [100, 50, 30],
... })
>>> fdf = fastmob.FlowDataFrame(flows)
>>> fdf.get_flow("A", "B")
50

get_flow(origin_id, destination_id)

Return the flow between two tile IDs (0 if no such pair exists).

Parameters:

Name Type Description Default
origin_id str

Origin tile identifier.

required
destination_id str

Destination tile identifier.

required

Returns:

Type Description
int or float

Flow value, or 0 if the pair is not present.

Examples:

>>> import pandas as pd
>>> import fastmob
>>> flows = pd.DataFrame({
...     "origin": ["A", "A", "B"],
...     "destination": ["A", "B", "A"],
...     "flow": [100, 50, 30],
... })
>>> fdf = fastmob.FlowDataFrame(flows)
>>> fdf.get_flow("A", "B")
50
>>> fdf.get_flow("B", "C")
0

get_geometry(tile_id)

Return the geometry of a tessellation tile.

Parameters:

Name Type Description Default
tile_id str

Identifier of the tile to look up.

required

Returns:

Type Description
shapely geometry

The geometry associated with tile_id in the tessellation.

Raises:

Type Description
ValueError

If no tessellation is attached or the tile ID is not found.

Examples:

>>> import fastmob
>>> fdf = fastmob.data.load_dataset("flow_foursquare_nyc")
>>> geom = fdf.get_geometry("36005")

plot_flows(map_f=None, min_flow=0, tiles='cartodbpositron', zoom=6, flow_color='red', opacity=0.5, flow_weight=5, flow_exp=0.5, style_function=None, flow_popup=False, num_od_popup=5, tile_popup=True, radius_origin_point=5, color_origin_point='#3186cc', control_scale=True)

Plot origin-destination flows on an interactive Folium map.

Requires a tessellation to be attached (see :meth:to_flowdataframe).

Parameters:

Name Type Description Default
map_f Map

Existing map. Creates a new map if None.

None
min_flow float

Only flows larger than this value are drawn. Default 0.

0
tiles str

Folium tile layer. Default 'cartodbpositron'.

'cartodbpositron'
zoom int

Initial zoom. Default 6.

6
flow_color str

Color for flow edges. Default 'red'.

'red'
opacity float

Edge opacity. Default 0.5.

0.5
flow_weight float

Weight factor for edge thickness. Default 5.

5
flow_exp float

Exponent for edge thickness scaling. Default 0.5.

0.5
style_function callable

Custom GeoJson style factory. Defaults to fastmob.utils.plot.flow_style_function.

None
flow_popup bool

Show a popup on edge click. Default False.

False
num_od_popup int

Number of OD pairs in origin popup. Default 5.

5
tile_popup bool

Show origin-tile popup. Default True.

True
radius_origin_point float

Radius of origin circle markers. Default 5.

5
color_origin_point str

Color of origin markers. Default '#3186cc'.

'#3186cc'
control_scale bool

Add a scale bar. Default True.

True

Returns:

Type Description
Map
Notes

Requires fastmob[visualization]::

pip install "fastmob[visualization]"

Examples:

>>> import fastmob
>>> fdf = fastmob.data.load_dataset("flow_foursquare_nyc")
>>> m = fdf.plot_flows(flow_color="red", zoom=10)

plot_tessellation(map_f=None, maxitems=-1, style_func_args={}, popup_features=[], tiles='cartodbpositron', zoom=6, geom_col='geometry', control_scale=True)

Plot the spatial tessellation on an interactive Folium map.

Parameters:

Name Type Description Default
map_f Map

Existing map. Creates a new map if None.

None
maxitems int

Maximum number of tiles to render. -1 renders all. Default -1.

-1
style_func_args dict

Style overrides: weight, color, opacity, fillColor, fillOpacity, radius.

{}
popup_features list

Tessellation columns to show in click popups.

[]
tiles str

Folium tile layer. Default 'cartodbpositron'.

'cartodbpositron'
zoom int

Initial zoom. Default 6.

6
geom_col str

Name of the geometry column in the tessellation. Default 'geometry'.

'geometry'
control_scale bool

Add a scale bar. Default True.

True

Returns:

Type Description
Map
Notes

Requires fastmob[visualization]::

pip install "fastmob[visualization]"

Examples:

>>> import fastmob
>>> fdf = fastmob.data.load_dataset("flow_foursquare_nyc")
>>> m = fdf.plot_tessellation(popup_features=["tile_id", "population"])

settings_from(other)

Copy metadata attributes from another FlowDataFrame.

Parameters:

Name Type Description Default
other FlowDataFrame

Source FlowDataFrame to copy attributes from.

required

Examples:

>>> import pandas as pd
>>> import fastmob
>>> flows = pd.DataFrame({"origin": ["A"], "destination": ["B"], "flow": [10]})
>>> fdf1 = fastmob.FlowDataFrame(flows.copy())
>>> fdf2 = fastmob.FlowDataFrame(flows.copy(), parameters={"year": 2020})
>>> fdf1.settings_from(fdf2)
>>> fdf1.parameters
{'year': 2020}

to_matrix()

Convert the flow table to a numpy matrix.

The rows and columns are ordered by the tile IDs in the tessellation (if present) or by the sorted union of all origin and destination IDs.

Returns:

Type Description
ndarray

Square flow matrix of shape (n_tiles, n_tiles).

Examples:

>>> import pandas as pd
>>> import fastmob
>>> flows = pd.DataFrame({
...     "origin": ["A", "A", "B"],
...     "destination": ["A", "B", "A"],
...     "flow": [100, 50, 30],
... })
>>> fdf = fastmob.FlowDataFrame(flows)
>>> fdf.to_matrix()
array([[100.,  50.],
       [ 30.,   0.]])

Query methods

API Description
FlowDataFrame.get_flow Return the flow between two tile IDs (0 if absent).
FlowDataFrame.get_geometry Return the geometry of a tessellation tile.
FlowDataFrame.settings_from Copy metadata attributes from another FlowDataFrame.

fastmob.core.flow_dataframe.FlowDataFrame.get_flow(origin_id, destination_id)

Return the flow between two tile IDs (0 if no such pair exists).

Parameters:

Name Type Description Default
origin_id str

Origin tile identifier.

required
destination_id str

Destination tile identifier.

required

Returns:

Type Description
int or float

Flow value, or 0 if the pair is not present.

Examples:

>>> import pandas as pd
>>> import fastmob
>>> flows = pd.DataFrame({
...     "origin": ["A", "A", "B"],
...     "destination": ["A", "B", "A"],
...     "flow": [100, 50, 30],
... })
>>> fdf = fastmob.FlowDataFrame(flows)
>>> fdf.get_flow("A", "B")
50
>>> fdf.get_flow("B", "C")
0

fastmob.core.flow_dataframe.FlowDataFrame.get_geometry(tile_id)

Return the geometry of a tessellation tile.

Parameters:

Name Type Description Default
tile_id str

Identifier of the tile to look up.

required

Returns:

Type Description
shapely geometry

The geometry associated with tile_id in the tessellation.

Raises:

Type Description
ValueError

If no tessellation is attached or the tile ID is not found.

Examples:

>>> import fastmob
>>> fdf = fastmob.data.load_dataset("flow_foursquare_nyc")
>>> geom = fdf.get_geometry("36005")

fastmob.core.flow_dataframe.FlowDataFrame.settings_from(other)

Copy metadata attributes from another FlowDataFrame.

Parameters:

Name Type Description Default
other FlowDataFrame

Source FlowDataFrame to copy attributes from.

required

Examples:

>>> import pandas as pd
>>> import fastmob
>>> flows = pd.DataFrame({"origin": ["A"], "destination": ["B"], "flow": [10]})
>>> fdf1 = fastmob.FlowDataFrame(flows.copy())
>>> fdf2 = fastmob.FlowDataFrame(flows.copy(), parameters={"year": 2020})
>>> fdf1.settings_from(fdf2)
>>> fdf1.parameters
{'year': 2020}

Conversion methods

API Description
FlowDataFrame.to_matrix Convert the flow table to a square numpy matrix.

fastmob.core.flow_dataframe.FlowDataFrame.to_matrix()

Convert the flow table to a numpy matrix.

The rows and columns are ordered by the tile IDs in the tessellation (if present) or by the sorted union of all origin and destination IDs.

Returns:

Type Description
ndarray

Square flow matrix of shape (n_tiles, n_tiles).

Examples:

>>> import pandas as pd
>>> import fastmob
>>> flows = pd.DataFrame({
...     "origin": ["A", "A", "B"],
...     "destination": ["A", "B", "A"],
...     "flow": [100, 50, 30],
... })
>>> fdf = fastmob.FlowDataFrame(flows)
>>> fdf.to_matrix()
array([[100.,  50.],
       [ 30.,   0.]])

Visualization methods

Visualization methods require the optional visualization extra:

pip install "fastmob[visualization]"
API Description
FlowDataFrame.plot_flows Plot origin-destination flows on an interactive Folium map.
FlowDataFrame.plot_tessellation Plot the spatial tessellation on an interactive Folium map.

fastmob.core.flow_dataframe.FlowDataFrame.plot_flows(map_f=None, min_flow=0, tiles='cartodbpositron', zoom=6, flow_color='red', opacity=0.5, flow_weight=5, flow_exp=0.5, style_function=None, flow_popup=False, num_od_popup=5, tile_popup=True, radius_origin_point=5, color_origin_point='#3186cc', control_scale=True)

Plot origin-destination flows on an interactive Folium map.

Requires a tessellation to be attached (see :meth:to_flowdataframe).

Parameters:

Name Type Description Default
map_f Map

Existing map. Creates a new map if None.

None
min_flow float

Only flows larger than this value are drawn. Default 0.

0
tiles str

Folium tile layer. Default 'cartodbpositron'.

'cartodbpositron'
zoom int

Initial zoom. Default 6.

6
flow_color str

Color for flow edges. Default 'red'.

'red'
opacity float

Edge opacity. Default 0.5.

0.5
flow_weight float

Weight factor for edge thickness. Default 5.

5
flow_exp float

Exponent for edge thickness scaling. Default 0.5.

0.5
style_function callable

Custom GeoJson style factory. Defaults to fastmob.utils.plot.flow_style_function.

None
flow_popup bool

Show a popup on edge click. Default False.

False
num_od_popup int

Number of OD pairs in origin popup. Default 5.

5
tile_popup bool

Show origin-tile popup. Default True.

True
radius_origin_point float

Radius of origin circle markers. Default 5.

5
color_origin_point str

Color of origin markers. Default '#3186cc'.

'#3186cc'
control_scale bool

Add a scale bar. Default True.

True

Returns:

Type Description
Map
Notes

Requires fastmob[visualization]::

pip install "fastmob[visualization]"

Examples:

>>> import fastmob
>>> fdf = fastmob.data.load_dataset("flow_foursquare_nyc")
>>> m = fdf.plot_flows(flow_color="red", zoom=10)

fastmob.core.flow_dataframe.FlowDataFrame.plot_tessellation(map_f=None, maxitems=-1, style_func_args={}, popup_features=[], tiles='cartodbpositron', zoom=6, geom_col='geometry', control_scale=True)

Plot the spatial tessellation on an interactive Folium map.

Parameters:

Name Type Description Default
map_f Map

Existing map. Creates a new map if None.

None
maxitems int

Maximum number of tiles to render. -1 renders all. Default -1.

-1
style_func_args dict

Style overrides: weight, color, opacity, fillColor, fillOpacity, radius.

{}
popup_features list

Tessellation columns to show in click popups.

[]
tiles str

Folium tile layer. Default 'cartodbpositron'.

'cartodbpositron'
zoom int

Initial zoom. Default 6.

6
geom_col str

Name of the geometry column in the tessellation. Default 'geometry'.

'geometry'
control_scale bool

Add a scale bar. Default True.

True

Returns:

Type Description
Map
Notes

Requires fastmob[visualization]::

pip install "fastmob[visualization]"

Examples:

>>> import fastmob
>>> fdf = fastmob.data.load_dataset("flow_foursquare_nyc")
>>> m = fdf.plot_tessellation(popup_features=["tile_id", "population"])