Reputation: 1
I am fairly new to SHAPEFiles and GeoDataFrames so apologies if this is a very basic question.
I am using Google Colab in Google Chrome on a Mac. Python version 3.xx
I have an existing Esri SHAPEFile that has CRS points (latitiude-longitude) of Polygons and MultiPolygons.
My objective was to find the centroid of these Polygons and MultiPolygons and add the centroids as a new column in the existing SHAPEfile and then save the file locally.
How do I save the file locally? What format do I use? Thanks.
Upvotes: 0
Views: 1025
Reputation: 10065
import geopandas as gpd
df = gpd.read_file("polygons.shp")
df["geometry"] = df["geometry"].centroid # assuming a projection CRS is used
df.to_file("centroids.shp", driver="Shapefile")
You'll need to refresh your working directory in Google Colabs to see the shapefile. Make sure you download all associated files as well.
Note: You cannot store more than one geometry in a shapefile.
The script creates a new shapefile using the centroids for the geometries but also keeping all other columns. That way you will be able to relate both datasets.
Here is a possible workflow:
polygons.zip
in my example!pip install geopandas
import os
import tempfile
import zipfile
import glob
import geopandas as gpd
OUTPUT_SHAPE_FILE = "centroids.shp"
SHAPE_FILE_ZIP = "polygons.zip"
with tempfile.TemporaryDirectory() as wd:
with zipfile.ZipFile(SHAPE_FILE_ZIP, "r") as shape_file_zip:
shape_file_zip.extractall(wd)
shape_file = os.path.join(wd, SHAPE_FILE_ZIP.replace(".zip", ".shp"))
df = gpd.read_file(shape_file)
df["geometry"] = df["geometry"].centroid # assuming a projection CRS is used
df.to_file(os.path.join(wd, OUTPUT_SHAPE_FILE), driver="Shapefile")
shape_file_name = OUTPUT_SHAPE_FILE.replace(".shp", "")
with zipfile.ZipFile(f"{shape_file_name}.zip", "w") as output_file:
for file in glob.iglob(f"{os.path.join(wd, shape_file_name)}.*"):
output_file.write(file, os.path.basename(file))
centroids.zip
PS. I would recommend to use a local Jupyter notebook and Python environment for such situations.
Upvotes: 1