I have a geopandas GeoDataFrame that consists of linestrings. Linstrings are of x, y…
- User
I have a geopandas GeoDataFrame that consists of linestrings. Linstrings are of x, y coords, whereas I need x, y, z. Write a loop that assigns z coord to each point in each linestring in the dataframe:
pythoncenterlines = gpd.GeoDataFrame(geometry=centerlines, crs=self.seg.crs).to_crs(self.chunk.shapes.crs.wkt)The z coord can be accesed via next method (it needs x and y):
pythonz = self.dem.altitude(Metashape.Vector((x, y))) Assistant
Here's the loop that should do what you need:
pythonimport geopandas as gpd # assuming centerlines is your GeoDataFrame for index, row in centerlines.iterrows(): linestring = row['geometry'] coords_2d = list(linestring.coords) coords_3d = [(x, y, self.dem.altitude(Metashape.Vector((x, y)))) for x, y in coords_2d] linestring_3d = gpd.GeoSeries(gpd.LineString(coords_3d)) centerlines.at[index, 'geometry'] = linestring_3dHere's what's happening:
- We iterate over each row in the GeoDataFrame using
iterrows(). - For each row, we extract the linestring geometry using
row['geometry']. - We convert the linestring to a list of 2D coordinates using
linestring.coords. - We create a new list of 3D coordinates by iterating over the 2D coordinates and adding the z-coordinate using your method.
- We iterate over each row in the GeoDataFrame using