Home
cd ../playbooks
Data & ReportingIntermediate

Scientific Geopandas

Python library for working with geospatial vector data including shapefiles, GeoJSON, and GeoPackage files. Use when working with geographic data for spatial analysis, geometric operations, coordinate transformations, spatial joins, overlay operat...

10 minutes
By K-Dense AISource
#scientific#claude-code#geopandas#visualization#database#protein#writing

You have shapefiles, GeoJSON, and GeoPackage files from different sources that need spatial joins, coordinate transformations, and overlay operations. GeoPandas extends pandas with geometry support so you can manipulate geospatial vector data as naturally as a regular DataFrame — no desktop GIS required.

Who it's for: GIS analysts performing spatial analysis in Python instead of desktop software, urban planners working with parcel and zoning shapefiles, environmental scientists overlaying field data with administrative boundaries, data scientists adding spatial dimensions to tabular datasets, transportation engineers analyzing road networks and service areas

Example

"Join our field sampling points to census tract boundaries and compute statistics per tract" → GeoPandas workflow: shapefile and GeoJSON loading with CRS alignment, spatial join of points to polygons, per-tract aggregation statistics, choropleth map visualization, and export to GeoPackage for sharing with GIS colleagues

CLAUDE.md Template

New here? 3-minute setup guide → | Already set up? Copy the template below.

# GeoPandas

GeoPandas extends pandas to enable spatial operations on geometric types. It combines the capabilities of pandas and shapely for geospatial data analysis.

## Installation

```bash
uv pip install geopandas
```

### Optional Dependencies

Get new playbooks like this one

One email a week with new Claude Code workflows. Free, like everything here.

No spam. Unsubscribe anytime.

README.md

What This Does

A scientific skill for geopandas workflows with Claude Code.


Quick Start

Step 1: Create a Project Folder

mkdir -p ~/Projects/geopandas

Step 2: Download the Template

Click Download above, then:

mv ~/Downloads/CLAUDE.md ~/Projects/geopandas/

Step 3: Start Claude Code

cd ~/Projects/geopandas
claude

GeoPandas extends pandas to enable spatial operations on geometric types. It combines the capabilities of pandas and shapely for geospatial data analysis.

Installation

uv pip install geopandas

Optional Dependencies

# For interactive maps
uv pip install folium

# For classification schemes in mapping
uv pip install mapclassify

# For faster I/O operations (2-4x speedup)
uv pip install pyarrow

# For PostGIS database support
uv pip install psycopg2
uv pip install geoalchemy2

# For basemaps
uv pip install contextily

# For cartographic projections
uv pip install cartopy

Core Concepts

Data Structures

  • GeoSeries: Vector of geometries with spatial operations
  • GeoDataFrame: Tabular data structure with geometry column

See data-structures.md for details.

Reading and Writing Data

GeoPandas reads/writes multiple formats: Shapefile, GeoJSON, GeoPackage, PostGIS, Parquet.

# Read with filtering
gdf = gpd.read_file("data.gpkg", bbox=(xmin, ymin, xmax, ymax))

# Write with Arrow acceleration
gdf.to_file("output.gpkg", use_arrow=True)

See data-io.md for comprehensive I/O operations.

Coordinate Reference Systems

Always check and manage CRS for accurate spatial operations:

# Check CRS
print(gdf.crs)

# Reproject (transforms coordinates)
gdf_projected = gdf.to_crs("EPSG:3857")

# Set CRS (only when metadata missing)
gdf = gdf.set_crs("EPSG:4326")

See crs-management.md for CRS operations.

Common Operations

Geometric Operations

Buffer, simplify, centroid, convex hull, affine transformations:

# Buffer by 10 units
buffered = gdf.geometry.buffer(10)

# Simplify with tolerance
simplified = gdf.geometry.simplify(tolerance=5, preserve_topology=True)

# Get centroids
centroids = gdf.geometry.centroid

See geometric-operations.md for all operations.

Spatial Analysis

Spatial joins, overlay operations, dissolve:

# Spatial join (intersects)
joined = gpd.sjoin(gdf1, gdf2, predicate='intersects')

# Nearest neighbor join
nearest = gpd.sjoin_nearest(gdf1, gdf2, max_distance=1000)

# Overlay intersection
intersection = gpd.overlay(gdf1, gdf2, how='intersection')

# Dissolve by attribute
dissolved = gdf.dissolve(by='region', aggfunc='sum')

See spatial-analysis.md for analysis operations.

Visualization

Create static and interactive maps:

# Choropleth map
gdf.plot(column='population', cmap='YlOrRd', legend=True)

# Interactive map
gdf.explore(column='population', legend=True).save('map.html')

# Multi-layer map
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
gdf1.plot(ax=ax, color='blue')
gdf2.plot(ax=ax, color='red')

See visualization.md for mapping techniques.

Detailed Documentation

  • Data Structures - GeoSeries and GeoDataFrame fundamentals
  • Data I/O - Reading/writing files, PostGIS, Parquet
  • Geometric Operations - Buffer, simplify, affine transforms
  • Spatial Analysis - Joins, overlay, dissolve, clipping
  • Visualization - Plotting, choropleth maps, interactive maps
  • CRS Management - Coordinate reference systems and projections

Common Workflows

Load, Transform, Analyze, Export

# 1. Load data
gdf = gpd.read_file("data.shp")

# 2. Check and transform CRS
print(gdf.crs)
gdf = gdf.to_crs("EPSG:3857")

# 3. Perform analysis
gdf['area'] = gdf.geometry.area
buffered = gdf.copy()
buffered['geometry'] = gdf.geometry.buffer(100)

# 4. Export results
gdf.to_file("results.gpkg", layer='original')
buffered.to_file("results.gpkg", layer='buffered')

Spatial Join and Aggregate

# Join points to polygons
points_in_polygons = gpd.sjoin(points_gdf, polygons_gdf, predicate='within')

# Aggregate by polygon
aggregated = points_in_polygons.groupby('index_right').agg({
    'value': 'sum',
    'count': 'size'
})

# Merge back to polygons
result = polygons_gdf.merge(aggregated, left_index=True, right_index=True)

Multi-Source Data Integration

# Read from different sources
roads = gpd.read_file("roads.shp")
buildings = gpd.read_file("buildings.geojson")
parcels = gpd.read_postgis("SELECT * FROM parcels", con=engine, geom_col='geom')

# Ensure matching CRS
buildings = buildings.to_crs(roads.crs)
parcels = parcels.to_crs(roads.crs)

# Perform spatial operations
buildings_near_roads = buildings[buildings.geometry.distance(roads.union_all()) < 50]

Performance Tips

  1. Use spatial indexing: GeoPandas creates spatial indexes automatically for most operations
  2. Filter during read: Use bbox, mask, or where parameters to load only needed data
  3. Use Arrow for I/O: Add use_arrow=True for 2-4x faster reading/writing
  4. Simplify geometries: Use .simplify() to reduce complexity when precision isn't critical
  5. Batch operations: Vectorized operations are much faster than iterating rows
  6. Use appropriate CRS: Projected CRS for area/distance, geographic for visualization

Best Practices

  1. Always check CRS before spatial operations
  2. Use projected CRS for area and distance calculations
  3. Match CRS before spatial joins or overlays
  4. Validate geometries with .is_valid before operations
  5. Use .copy() when modifying geometry columns to avoid side effects
  6. Preserve topology when simplifying for analysis
  7. Use GeoPackage format for modern workflows (better than Shapefile)
  8. Set max_distance in sjoin_nearest for better performance

$Related Playbooks

Data & Reporting

Scientific Hypogenic

Automated LLM-driven hypothesis generation and testing on tabular datasets. Use when you want to systematically explore hypotheses about patterns in empirical data (e.g., deception detection, content analysis). Combines literature insights with da...

15 minutes
Advanced
Data & Reporting

Scientific Infographics

'Create professional infographics using Nano Banana Pro AI with smart iterative refinement. Uses Gemini 3 Pro for quality review. Integrates research-lookup and web search for accurate data. Supports 10 infographic types, 8 industry styles, and co...

10 minutes
Intermediate
Data & Reporting

Excel File Manipulation

Create, edit, and manipulate Excel spreadsheets programmatically using openpyxl

10 minutes
Intermediate
Data & Reporting

Agency Dashboard

Portfolio-level client overview.

15 minutes
Intermediate
Data & Reporting

Competitor Monitor

Set up ongoing competitor monitoring.

15 minutes
Intermediate
Data & Reporting

Analytics Insights

Analyze marketing performance.

15 minutes
Intermediate
Data & Reporting

Anomaly Scan

Detect marketing anomalies.

15 minutes
Intermediate
Data & Reporting

Client Report

Generate client-facing reports.

15 minutes
Intermediate
Data & Reporting

Chart & Data Visualization Designer

Design effective data visualizations and charts. Generate chart configurations for ECharts, Chart.js, and other libraries. Create dashboards and reports.

10 minutes
Intermediate
Data & Reporting

Data Question Analyzer

Answer data questions ranging from quick lookups to formal analytical reports

10 minutes
Intermediate
Data & Reporting

Data Visualization Creator

Create publication-quality data visualizations with matplotlib, plotly, or Chart.js

10 minutes
Intermediate
Data & Reporting

Dataset Explorer

Profile datasets to understand shape, quality, distributions, and key patterns

10 minutes
Beginner

Browse all Data & Reporting playbooks →