group-bygeopandas

How to groupby and unionize polygons in geopandas by a certain category?


I'm trying to groupby polygons that belong to a certain block group which I can then use to make a visualization.

import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
from dateutil.parser import parse 

import geopandas as gpd
from shapely.geometry import Point, Polygon

shp = gpd.read_file("Data/SD_Census_Block_Groups.shp")

# Rename GEOID to bg_orig
shp = shp.rename({'GEOID': 'bg_orig'}, axis='columns')

shp.head(10)

Let's say I want to do a groupby of the geometry column with the column NAMELSAD which has the Block Group labels. So any row in a certain Block Group will be unionized.


Solution

  • You are looking for dissolve.

    result = shp.dissolve(by='NAMELSAD')
    

    Reference: https://geopandas.readthedocs.io/en/latest/docs/reference/api/geopandas.GeoDataFrame.dissolve.html#geopandas.GeoDataFrame.dissolve