2

I have a geodataframe that contains positions (point geometries). For each position, we know the individual's id (id_individ), DOY (doy), year (année) and timestamp.

entry

I want to aggregate the geometries (and sort them by timestamp) to reconstitute individual tracks, grouped by id and DOY. The expected result is a geodataframe where the geometry column contains Linestrings. So far, I've tried this python command:

tracks = gpd.GeoDataFrame(df_species.groupby(['id_individ', 'doy', 'year']).geometry.agg(unary_union).reset_index(), geometry="geometry", crs=df_species.crs)

I get :

Output

I can't sort the points by timestamp at aggregation time and then generate a Linestring. I know it's possible to do this in SQL, but I'm looking for a way to do it in Python with Geopandas.

1 Answer 1

5

Sort by id and date, groupby id and agg into linestrings:

import geopandas as gpd
from shapely.geometry import LineString

df = gpd.read_file(r"/home/bera/Desktop/gistest/gps_points.shp")

#A set of points for two id's with a date column    :

#df.head()
    #     id                   geometry       date
    # 36   1  POINT (-8.13625 54.75627) 2020-01-17
    # 17   2  POINT (11.42834 45.70536) 2022-03-18
    # 15   2  POINT (13.65557 48.35051) 2022-03-16
    # 32   1  POINT (-9.85519 63.64919) 2020-01-13
    # 2    2  POINT (12.77191 52.25444) 2022-03-03
    

#Sort by id and date, groupby id and pass all the points for each id to LineString
df2 = df.sort_values(by=["id","date"]).groupby("id", as_index=False).agg({"geometry":lambda x: LineString(x)})

#The geometry column definition and crs gets lost, reset them:
df2 = df2.set_geometry("geometry") 
df2 = df2.set_crs("EPSG:4326")

#df2
#    id                                           geometry
# 0   1  LINESTRING (-17.97494 65.30383, -17.23383 66.3...
# 1   2  LINESTRING (9.55470 55.21967, 10.83302 53.2404...

enter image description here

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.