Skip to content

Instantly share code, notes, and snippets.

@tommylees112
Created December 21, 2024 23:07
Show Gist options
  • Save tommylees112/a71d72dc0c654796154f443e69f7437f to your computer and use it in GitHub Desktop.
Save tommylees112/a71d72dc0c654796154f443e69f7437f to your computer and use it in GitHub Desktop.
from geopandas import GeoDataFrame
from typing import Union
import pandas as pd
def geodf_to_wkt_csv(gdf: GeoDataFrame, output_file: Union[str, None] = None) -> pd.DataFrame:
"""
Converts a GeoDataFrame's geometry column to WKT format and optionally saves it to a CSV file.
Args:
gdf (GeoDataFrame): The input GeoDataFrame to be converted.
output_file (Union[str, None]): The file path to save the resulting CSV. If None, the file is not saved.
Returns:
pd.DataFrame: A pandas DataFrame with the geometry column converted to WKT.
"""
# Convert the geometry column to WKT
df = gdf.copy()
df["geometry"] = df["geometry"].apply(lambda geom: geom.wkt)
# Save to CSV if an output file is provided
if output_file:
df.to_csv(output_file, index=False)
return df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment