The following examples show how to find a mover's position at a certain time or for a certain time span.
import pandas as pd
import geopandas as gpd
from geopandas import GeoDataFrame, read_file
from shapely.geometry import Point, LineString, Polygon
from datetime import datetime, timedelta
import movingpandas as mpd
import warnings
warnings.filterwarnings('ignore')
print(f'MovingPandas version {mpd.__version__}')
First, let's create a basic trajectory:
df = pd.DataFrame([
{'geometry':Point(0,0), 't':datetime(2018,1,1,12,0,0)},
{'geometry':Point(6,0), 't':datetime(2018,1,1,12,6,0)},
{'geometry':Point(6,6), 't':datetime(2018,1,1,12,10,0)},
{'geometry':Point(9,9), 't':datetime(2018,1,1,12,15,0)}
]).set_index('t')
gdf = GeoDataFrame(df, crs=31256)
toy_traj = mpd.Trajectory(gdf, 1)
toy_traj
help(mpd.Trajectory.get_position_at)
When we call this method, the resulting point is directly rendered:
toy_traj.get_position_at(datetime(2018,1,1,12,6,0), method="nearest")
To see its coordinates, we can look at the print output:
print(toy_traj.get_position_at(datetime(2018,1,1,12,6,0), method="nearest"))
The method parameter describes what the function should do if there is no entry in the trajectory GeoDataFrame for the specified timestamp.
For example, there is no entry at 2018-01-01 12:07:00
toy_traj.df
t = datetime(2018,1,1,12,7,0)
print(toy_traj.get_position_at(t, method="nearest"))
print(toy_traj.get_position_at(t, method="interpolated"))
print(toy_traj.get_position_at(t, method="ffill")) # from the previous row
print(toy_traj.get_position_at(t, method="bfill")) # from the following row
point = toy_traj.get_position_at(t, method="interpolated")
df = pd.DataFrame([{'id': toy_traj.id, 'geometry': point, 't': t}])
gdf = GeoDataFrame(df, crs=toy_traj.crs)
ax = toy_traj.plot()
gdf.plot(ax=ax, color='red', markersize=100)
ax = toy_traj.plot()
First, let's extract the trajectory segment for a certain time period:
help(mpd.Trajectory.get_segment_between)
segment = toy_traj.get_segment_between(datetime(2018,1,1,12,6,0), datetime(2018,1,1,12,12,0))
print(segment)
ax = toy_traj.plot()
segment.plot(ax=ax, color='red', linewidth=5)
Now, let's extract the trajectory segment that intersects with a given polygon:
xmin, xmax, ymin, ymax = 2, 8, -10, 5
polygon = Polygon([(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin), (xmin, ymin)])
polygon
polygon_gdf = GeoDataFrame(pd.DataFrame([{'geometry':polygon, 'id':1}]), crs=31256)
help(mpd.Trajectory.clip)
intersections = toy_traj.clip(polygon)
intersections
ax = toy_traj.plot()
polygon_gdf.plot(ax=ax, color='lightgray')
intersections.plot(ax=ax, color='red', linewidth=5, capstyle='round')