GeoPandas and Shapely: Vector Data in Python

GeoPandas and Shapely: Vector Data in Python

If I had to pick the single most valuable library for a GIS analyst who has just learned a little Python, I would pick GeoPandas without hesitation. It takes something that every analyst already understands, a table with rows and columns, and adds one extra column that holds geometry. Suddenly all the data-wrangling power of Python, the filtering, grouping, joining and summarizing that spreadsheet users dream of, works on maps. A task that takes ten clicks in a desktop GIS, buffer, join, dissolve, calculate a field, becomes one readable line, and the line can run on ten thousand files.

Underneath, GeoPandas relies on Shapely, which provides the geometry objects and the geometric operations. Understanding both, and how they fit together, is the foundation of vector analysis in Python. In this guide I’ll walk you through the data model, the essential operations with working examples, spatial joins and overlays, performance tips, and the pitfalls that catch nearly everyone once.

If you are new to Python, start with Python for GIS: Getting Started. For the wider ecosystem, see Geospatial Development & Automation: The Ultimate Guide.

Diagram: A GeoPandas script reads data, fixes the CRS, applies geometry operations, joins by location and writes the result.
A GeoPandas script reads data, fixes the CRS, applies geometry operations, joins by location and writes the result.

The Data Model: GeoSeries and GeoDataFrame

Shapely: the geometry objects

Shapely represents individual geometries.

  • Point: one location.
  • LineString: an ordered sequence of points.
  • Polygon: an area bounded by a ring, possibly with holes.
  • MultiPoint, MultiLineString, MultiPolygon: collections of the above, treated as one feature.
  • GeometryCollection: a mixed bag.
from shapely.geometry import Point, LineString, Polygon

p = Point(2.35, 48.85)
line = LineString([(0, 0), (5, 5), (10, 0)])
poly = Polygon([(0, 0), (0, 10), (10, 10), (10, 0)])

print(poly.area, poly.length)               # 100.0 40.0
print(poly.contains(Point(5, 5)))           # True
print(line.distance(Point(0, 5)))           # shortest distance
print(poly.bounds)                          # (minx, miny, maxx, maxy)
print(poly.wkt)                             # text representation

Shapely knows nothing about coordinate systems. It treats coordinates as plain numbers on a flat plane. That is why you must project your data to a suitable CRS before measuring. In Shapely 2 and later, geometries are immutable: operations return new geometries and never change the original.

GeoPandas: tables with geometry

  • GeoSeries: a column of geometries, with a CRS.
  • GeoDataFrame: a pandas DataFrame with a special geometry column (a GeoSeries) and a CRS.

All pandas operations work, and extra spatial ones are added.

import geopandas as gpd

districts = gpd.read_file("districts.gpkg")
print(districts.head())          # attribute table, with the geometry column
print(districts.crs)             # coordinate reference system
print(districts.geometry.geom_type.value_counts())
print(districts.total_bounds)    # [minx, miny, maxx, maxy]
print(districts.dtypes)          # field types

Reading and Writing Data

# Read
gdf = gpd.read_file("data.gpkg")                      # layer by default
gdf = gpd.read_file("data.gpkg", layer="roads")       # a named layer
gdf = gpd.read_file("data.shp", encoding="utf-8")     # set the encoding if text looks garbled
gdf = gpd.read_file("data.gpkg", bbox=(2.2, 48.8, 2.5, 48.9))   # only features in a box
gdf = gpd.read_file("data.gpkg", columns=["name", "geometry"])  # only some fields (check support for your version)

# Write
gdf.to_file("out.gpkg", layer="roads", driver="GPKG")   # a layer inside a GeoPackage
gdf.to_file("out.geojson", driver="GeoJSON")

GeoPackage can hold many layers in one file, so you can add several to_file calls with different layer names. For the reasons to prefer it over Shapefile, see Shapefile vs. GeoJSON vs. GeoPackage: Which Format to Use?

Reading from and writing to PostGIS

With a SQLAlchemy connection, GeoPandas talks to a spatial database:

from sqlalchemy import create_engine

engine = create_engine("postgresql://user:password@localhost:5432/gis")

roads = gpd.read_postgis("SELECT id, name, geom FROM roads WHERE class = 'primary'",
                         engine, geom_col="geom")

roads.to_postgis("primary_roads", engine, if_exists="replace")

Never hardcode passwords in scripts you share. Use environment variables or a configuration file. See PostGIS: A Practical Introduction and Spatial SQL Cheat Sheet.


Coordinate Reference Systems: set_crs vs. to_crs

This pair is the single most important distinction in the library.

  • set_crs declares what CRS the coordinates are already in. Use it only when the CRS is missing or wrong. It changes no numbers.
  • to_crs converts the coordinates to another CRS. It recalculates every vertex.
print(gdf.crs)                              # None? The label is missing.
gdf = gdf.set_crs("EPSG:4326")              # declare it, if you KNOW it is WGS 84

gdf_m = gdf.to_crs(epsg=32631)              # convert to UTM 31N (choose one for your area)

Mistaking one for the other is the most frequent way to corrupt a dataset. Assigning a wrong CRS doesn’t fix the data. It ruins its meaning. For the theory, see Coordinate Reference Systems (CRS) Explained Simply and Map Projections: How to Choose the Right One.

The golden rule

Before any distance, area or buffer, make sure the data is in a projected CRS with meters. Check with gdf.crs and gdf.crs.axis_info, or gdf.crs.is_projected.


Everyday Operations

Selecting and filtering

big = districts[districts["population"] > 50000]                  # attribute filter
north = districts.cx[:, 48.9:]                                    # spatial slice by coordinates (xmin:xmax, ymin:ymax)
selected = districts.query("region == 'North' and population > 20000")

Creating and calculating columns

districts_m = districts.to_crs(epsg=32631)
districts_m["area_km2"] = districts_m.area / 1e6
districts_m["density"] = districts_m["population"] / districts_m["area_km2"]
districts_m["centroid"] = districts_m.centroid        # a column of point geometries

Geometry operations

buffers = gdf_m.copy()
buffers["geometry"] = gdf_m.buffer(100)               # 100 m buffer, valid only in a projected CRS in meters

simple = gdf_m.simplify(tolerance=10)                 # simplify lines and polygons (tolerance in CRS units)
hulls = gdf_m.convex_hull
inside = gdf_m.representative_point()                 # a point guaranteed to lie inside each polygon
boundary = gdf_m.boundary
parts = gdf_m.explode(index_parts=False)              # split multipart features into single parts

Use representative_point() instead of centroid when you need a point that is always inside an irregular polygon.

Measuring

gdf_m.area            # polygon areas
gdf_m.length          # line lengths, or polygon perimeters
a = gdf_m.geometry.iloc[0]
b = gdf_m.geometry.iloc[1]
a.distance(b)         # distance between two geometries
gdf_m.distance(point) # distance from every feature to a Shapely geometry

Spatial predicates

Boolean tests between geometries: intersects, contains, within, touches, crosses, overlaps, covers, disjoint.

mask = roads.intersects(flood_zone.union_all())       # which roads touch the flood zone (older versions: unary_union)
exposed_roads = roads[mask]

These are the building blocks that tools such as Select by Location use. See How Does GIS Work? Layers, Data, and Analysis Explained for the concepts.


Spatial Joins: Combining Layers by Location

A spatial join transfers attributes from one layer to another based on how their geometries relate. This is the operation you will use most.

Points in polygons

districts = gpd.read_file("districts.gpkg").to_crs(32631)
schools = gpd.read_file("schools.gpkg").to_crs(districts.crs)   # same CRS first!

joined = gpd.sjoin(
    schools,
    districts[["district_id", "name", "geometry"]],
    how="left",
    predicate="within"
)

# Count schools per district and attach to the districts
counts = joined.groupby("district_id").size().rename("n_schools")
districts = districts.merge(counts, on="district_id", how="left")
districts["n_schools"] = districts["n_schools"].fillna(0).astype(int)

Nearest feature

hospitals = gpd.read_file("hospitals.gpkg").to_crs(32631)

nearest = gpd.sjoin_nearest(
    schools,
    hospitals[["hospital_id", "geometry"]],
    how="left",
    distance_col="dist_m"
)
print(nearest["dist_m"].describe())

sjoin_nearest adds the nearest hospital and the distance, in CRS units, to each school. Remember that it measures straight-line distance. For travel along roads, use network analysis. See Network Analysis and Route Optimization.

Watch out for duplicates

A spatial join can produce more rows than you started with. If a point lies on the border of two polygons, or a polygon intersects several others, it will appear several times. Always compare the number of rows before and after, and decide how to handle repeats. For example, drop duplicates or aggregate.


Overlay Operations

The set-theory tools described in Buffer, Clip, Intersect, Union: Overlay Tools Explained are all available.

# Clip one layer to the shape of another
roads_in_area = gpd.clip(roads, study_area)

# Overlay: intersection, union, difference, symmetric_difference, identity
parcels_in_flood = gpd.overlay(parcels, flood_zones, how="intersection")
parcels_in_flood["overlap_ha"] = parcels_in_flood.area / 10000

# Dissolve: merge features that share an attribute value
regions = districts.dissolve(by="region", aggfunc={"population": "sum"})
regions = regions.reset_index()

Several cautions:

  • Both layers must share the same CRS.
  • Overlay is slow on huge, complex layers. Clip to your study area first, and use a spatial index.
  • Invalid geometries will cause errors. See below.
  • clip keeps only the input layer’s attributes. overlay keeps those of both.

Geometry Validity

Invalid geometries, such as self-intersecting polygons, are the main cause of mysterious errors.

invalid = gdf[~gdf.is_valid]
print(len(invalid), "invalid geometries")

# See why
from shapely.validation import explain_validity
print(explain_validity(invalid.geometry.iloc[0]))

# Repair them
from shapely import make_valid
gdf["geometry"] = gdf.geometry.apply(make_valid)

make_valid (available in Shapely 2) repairs geometries without throwing away parts, and is preferable to the old buffer(0) trick, which can silently drop pieces. Run a validity check after every import and before every overlay. See Top 10 Most Common GIS Errors and How to Fix Them.


Working With Points, Lines and WKT

import pandas as pd
from shapely import wkt

# Points from coordinates
df = pd.read_csv("stations.csv")
stations = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.lon, df.lat), crs="EPSG:4326")

# Geometries from WKT text
df["geometry"] = df["wkt"].apply(wkt.loads)
gdf = gpd.GeoDataFrame(df, geometry="geometry", crs="EPSG:4326")

# Lines from ordered points, one line per track
from shapely.geometry import LineString

tracks = (
    stations.sort_values("time")
    .groupby("track_id")["geometry"]
    .apply(lambda pts: LineString(pts.tolist()) if len(pts) > 1 else None)
)

These patterns convert tables of coordinates, which are everywhere, into spatial layers.


Plotting and Exploring

# A quick map, with a classification (needs the mapclassify package)
ax = districts_m.plot(column="density", scheme="quantiles", k=5, cmap="YlOrRd",
                      legend=True, edgecolor="white", linewidth=0.3, figsize=(8, 8))
ax.set_axis_off()

# An interactive web map in a notebook (needs folium and mapclassify)
districts_m.explore(column="density", cmap="YlOrRd", tooltip=["name", "density"])

For the cartographic principles that make plots clear, see Cartography Principles: Designing Maps That Communicate, Color Theory for Maps and Choropleth, Heat, and Proportional Symbol Maps: When to Use Each.


Performance: Making It Fast

Vector analysis in Python is fast when you use it the intended way.

  • Think in columns, not rows. Operations such as gdf.buffer(100) and gdf.area work on all features at once, in compiled code. A Python loop over rows is far slower. If you find yourself writing for index, row in gdf.iterrows(), look for a vectorized alternative first.
  • Use the spatial index. GeoPandas builds an R-tree spatial index (gdf.sindex) used automatically by joins and clips. For custom code, gdf.sindex.query(geometry) quickly finds candidate features.
  • Filter early. Read only the columns and the area you need, using bbox or columns while reading, or an SQL filter.
  • Clip big layers to your study area before heavy operations.
  • Simplify geometry for display, not for analysis.
  • Use efficient formats: GeoPackage or GeoParquet instead of Shapefile or text.
  • For data that does not fit in memory, use a spatial database such as PostGIS and let it do the heavy work, or process in chunks. See Enterprise GIS & Spatial Databases: PostGIS, Geodatabases, and Server Architecture.
  • Avoid unnecessary copies of big GeoDataFrames.
  • Test on a sample before the full run.

A Worked Example: Flood Exposure by Municipality

Question: how many buildings, and what building area, lie in the flood zone, for each municipality?

import geopandas as gpd
from shapely import make_valid

# 1. Read and harmonize
munis = gpd.read_file("data/municipalities.gpkg")
buildings = gpd.read_file("data/buildings.gpkg").to_crs(munis.crs)
flood = gpd.read_file("data/flood_zone.gpkg").to_crs(munis.crs)

# 2. Make sure the CRS is projected and in meters
assert munis.crs.is_projected, "Reproject to a projected CRS first"

# 3. Repair geometry
for layer in (buildings, flood):
    layer["geometry"] = layer.geometry.apply(make_valid)

# 4. Find the buildings that touch the flood zone
flood_union = flood.union_all()      # in GeoPandas versions before 1.0, use .unary_union
exposed = buildings[buildings.intersects(flood_union)].copy()
exposed["footprint_m2"] = exposed.area

# 5. Assign each exposed building to a municipality (representative point avoids ties)
exposed["geometry"] = exposed.representative_point()
by_muni = gpd.sjoin(exposed, munis[["muni_id", "name", "geometry"]], predicate="within", how="left")

# 6. Summarize
summary = (by_muni.groupby(["muni_id", "name"])
           .agg(n_buildings=("footprint_m2", "size"), area_m2=("footprint_m2", "sum"))
           .reset_index())

# 7. Attach the totals to the municipality polygons and save
result = munis.merge(summary[["muni_id", "n_buildings", "area_m2"]], on="muni_id", how="left").fillna(0)
result.to_file("outputs/flood_exposure.gpkg", driver="GPKG")

The structure is typical: read and harmonize, repair, analyze, summarize, save. Because it is code, you can rerun it when the flood map is updated. See GIS in Disaster Management and Emergency Response for the context.


Common Pitfalls

  • Forgetting the CRS. sjoin, overlay and clip expect the same CRS in both layers, and GeoPandas will warn or give wrong results otherwise.
  • Measuring in degrees. Areas and buffers in EPSG:4326 are meaningless.
  • set_crs instead of to_crs.
  • Invalid geometries.
  • Unintended row multiplication after a join.
  • Mixed geometry types in one layer, which some formats can’t store. Use explode or split by type.
  • Shapefile limits: ten-character field names, encoding trouble and no date-time fields. Prefer GeoPackage.
  • Writing datetime columns, which some drivers handle poorly. Convert to text or use a driver that supports them.
  • Chained assignment warnings. Use .copy() when you create a modified subset, and assign with .loc.
  • Index misalignment. After filtering or joining, indexes may not match. Use reset_index(drop=True) when appropriate.
  • Loading huge files into memory and wondering why the computer freezes.
  • Ignoring warnings. They are there for a reason.

Where to Go From Here


Final Thoughts

GeoPandas and Shapely give you a clean, expressive language for vector analysis. Once you are comfortable with a GeoDataFrame, you stop thinking about tools and start thinking about questions: which of these overlaps with that, how many, how far, how much. The code reads almost like the question itself, and because it is code, it is documented, repeatable and shareable.

Take a task you did last week in your desktop GIS, a join, a clip, a summary, and write it in GeoPandas. Run it twice, with a different input, and notice how effortless the second run is. That is the moment you will start to automate everything.

Where to go next: continue with Raster Processing in Python: Rasterio, Xarray, and NDVI from Code, and bring your vector skills to databases with Spatial SQL Cheat Sheet.

Rachid Khouri

Rachid Khouri

Rachid Khouri is a CAD, BIM and GIS professional, Autodesk Authorized Developer, trainer and technical author with more than 30 years of experience, working with AutoCAD since 1992. He founded GISauthority.com to share practical guidance on GIS and spatial technologies.