Reputation: 306
I have a dataframe with a column of linestrings. I want to convert the linestrings to its corresponding latitude/longitude so that I can plot it with basemap. My code is as follows:
gdf = gpd.read_file('./call2016.shp') #read the data into a variable
streetsaslinestring = gdf.loc[: , "geometry"] #getting the linestring column
Next, I want to convert the data as described as lon/lat.
streetsinlatlong = convert_etrs89_to_lonlat(streetsaslinestring)
streetsinlatlong.to_file('./streetslonglat.shp') #store it as .shp in order to plot it with basemap
m.readshapefile('./streetslonglat', 'streets') #read as shape file
The geometry column looks like this:geometry column
How can I convert the longstring data?
Upvotes: 2
Views: 2551
Reputation: 141
Thanks to @Clarence Kuo, this is the helper function I created for when I had the same question as the OP: extracting the latitude and longitude from a WKT LINESTRING Geometry object in GeoPandas:
import pandas as pd
from shapely import wkt
from typing import Tuple
def expand_max_min_lat_long_from_wkt(df: pd.DataFrame, wkt_col_name: str) -> pd.DataFrame:
def _check_n_correct_wkt(df: pd.DataFrame, wkt_col_name: str) -> Tuple[pd.DataFrame, str]:
if str(df[wkt_col_name].dtype) != 'geometry':
new_wkt_col_name = f"{wkt_col_name}__WKT"
df[new_wkt_col_name] = df[wkt_col_name].apply(wkt.loads)
wkt_col_name = new_wkt_col_name
return df, wkt_col_name
def _expand_max_min_lat_long_from_wkt(wkt_val) -> tuple:
if not wkt_val:
return (None, None, None, None)
lon, lat = wkt_val.coords.xy
return (
min(lat),
max(lat),
min(lon),
max(lon),
)
df, wkt_col_name = _check_n_correct_wkt(df, wkt_col_name)
(
df[f"{wkt_col_name}__LAT_MIN"],
df[f"{wkt_col_name}__LAT_MAX"],
df[f"{wkt_col_name}__LONG_MIN"],
df[f"{wkt_col_name}__LONG_MAX"],
) = zip(*df[wkt_col_name].apply(_expand_max_min_lat_long_from_wkt))
return df
With usage of:
gdf = expand_max_min_lat_long_from_wkt(gdf, 'geometry')
Upvotes: 1
Reputation: 31
I think you can simply use
Lats, Lons = LineStringObject.coords.xy
It will return the latitude and longitude array separately.
Upvotes: 3