Calculating Polygon Area in GeoDataFrame

  • Share this:

Code introduction


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