You can download this code by clicking the button below.
This code is now available for download.
This function calculates the area of each polygon in a GeoDataFrame. It first checks if the GeoDataFrame has a 'geometry' column, then calculates the area using the `.area` attribute and adds the result to a new column.
Technology Stack : GeoPandas, NumPy
Code Type : GeoPandas Function
Code Difficulty : Intermediate
import geopandas as gpd
import numpy as np
def calculate_area_of_polygons(gdf):
"""
This function calculates the area of each polygon in a GeoDataFrame.
"""
# Ensure the GeoDataFrame has a geometry column
if 'geometry' not in gdf.columns:
raise ValueError("The GeoDataFrame must have a 'geometry' column.")
# Calculate the area for each polygon
gdf['area'] = gdf.geometry.area
return gdf