GeoPandas Basics: Working with Spatial Data in Python

On this page

Problem statement

Ask Geofabrik's Rutland extract for its residential land and GeoPandas answers 159 polygons and 1,594 ha. A quarter of that is Stamford, a Lincolnshire town of which 3.3 ha crosses the county border; in all, 2,586 ha of the extract's land use lies outside Rutland. Nothing in the read, the filter or the write says so.

This page is a first GeoPandas session on that extract β€” read, inspect, check the CRS, filter, save β€” that stops at each line's output, then measures the extract against Rutland's 15 wards and finds 1,167 ha of residential land inside them.

Quick answer

Read, inspect, check the CRS, filter, save β€” five lines on a GeoDataFrame, a pandas table with a geometry column (what a GeoDataFrame is):

import geopandas as gpd

landuse = gpd.read_file("data/rutland/gis_osm_landuse_a_free_1.shp")
print(len(landuse), "polygons in", landuse.crs)

residential = landuse[landuse["fclass"] == "residential"]
residential.to_file("output/residential.geojson", driver="GeoJSON")
print(len(residential), "residential polygons written")
2405 polygons in EPSG:4326
159 residential polygons written

Rutland is England's smallest historic county; the file is its Geofabrik shapefile extract, which The data used on this page downloads. Those 159 polygons include Stamford's, which is in Lincolnshire β€” Example 1 finds them.

The vector workflow pipeline

The vector workflowread_file()InspectCheck.crsFilterPlotto_file()spatialworkflow.io
The core vector workflow, from reading a file to exporting.

Read, inspect, check the CRS, filter, plot, save

A GeoDataFrame is a pandas DataFrame plus an active geometry column. what you get back from read_file()namepopulationgeometryOslo709 037POINT (10.75 59.91)Bergen286 930POINT (5.32 60.39)Trondheim205 163POINT (10.40 63.43)active geometry β€” this column carries the CRSEverything you know about pandas still applies to the other columns spatialworkflow.io
One special column is the entire difference between a DataFrame and a GeoDataFrame.

Read a shapefile or GeoJSON into a GeoDataFrame

gpd.read_file() reads both formats used here (installing it: setting up a Python GIS environment).

Read a shapefile

A shapefile is several files side by side (.shp, .shx, .dbf, .prj, often .cpg); you point read_file() at the .shp and it finds the rest.

import geopandas as gpd

landuse = gpd.read_file("data/rutland/gis_osm_landuse_a_free_1.shp")
print(landuse.head())
    osm_id  code          fclass                     name                                 geometry
0  3554658  7210  nature_reserve                 Lagoon 3  POLYGON ((-0.69395 52.6626, -0.69361...
1  3554659  7210  nature_reserve                 Lagoon 2  POLYGON ((-0.70015 52.65614, -0.6991...
2  3700148  7202            park                      NaN  POLYGON ((-0.74126 52.66536, -0.7410...
3  3700814  7202            park  Royce Recreation Ground  POLYGON ((-0.74212 52.67041, -0.7405...
4  3700816  7202            park                      NaN  POLYGON ((-0.74291 52.66793, -0.7424...

Read a GeoJSON file

The second layer is Rutland's 15 electoral wards from the ONS boundary service, saved as GeoJSON.

wards = gpd.read_file("data/rutland_wards.geojson")
print(wards.head())
      WD24CD                     WD24NM                                 geometry
0  E05012632               Barleythorpe  POLYGON ((-0.72525 52.68542, -0.7243...
1  E05012633  Braunston & Martinsthorpe  POLYGON ((-0.75976 52.65781, -0.7594...
2  E05012634                 Cottesmore  POLYGON ((-0.67132 52.75641, -0.6707...
3  E05012635                      Exton  POLYGON ((-0.70772 52.72347, -0.709 ...
4  E05012636                   Greetham  POLYGON ((-0.60859 52.75971, -0.6054...

Each call returns a GeoDataFrame; the details of each format are in reading a shapefile and reading GeoJSON.

Inspect the GeoDataFrame structure

Look before using anything:

print(landuse.columns.tolist())
print(landuse.dtypes)
print("geometry column:", landuse.geometry.name)
print(len(landuse), "rows")
['osm_id', 'code', 'fclass', 'name', 'geometry']
osm_id           str
code           int32
fclass           str
name             str
geometry    geometry
dtype: object
geometry column: geometry
2405 rows

Five columns and 2,405 rows. Geofabrik's code is a numeric version of the fclass text, and one column is mostly empty:

print(landuse["name"].isna().sum(), "of", len(landuse), "polygons have no name")
2165 of 2405 polygons have no name

A filter on name would silently skip 91% of the county's land use. Exploring an unfamiliar dataset turns this look into a routine.

Check the coordinate reference system

Both layers report their CRS:

print(landuse.crs)
print(wards.crs)
EPSG:4326
EPSG:4326

Both are EPSG:4326. Measure the land use after to_crs(27700), British National Grid:

print(f"{landuse.to_crs(27700).area.sum() / 1e6:,.1f} kmΒ² of mapped land use")
268.9 kmΒ² of mapped land use

That is the extract's land use, not the county's: Example 1 shows how much of it lies over the border. Projected vs geographic CRS is why the reprojection comes first.

Rutland OpenStreetMap land-use polygons by fclass: forest 1,247, grass 323, farmland 241, residential 159. 2,405 land-use polygons in Rutland, by fclassforest1,247grass323farmland241residential159scrub93farmyard90park40meadow37other classes17507001400value_counts() before filtering: the class you want may be a small share spatialworkflow.io
What value_counts() shows before the filter: residential is 159 of 2,405 polygons, and forest outnumbers everything else combined.

Filter spatial records

Look at what values a field holds before filtering on it:

print(landuse["fclass"].value_counts().head(8))
fclass
forest         1247
grass           323
farmland        241
residential     159
scrub            93
farmyard         90
park             40
meadow           37
Name: count, dtype: int64

Example: keep only residential land

residential = landuse[landuse["fclass"] == "residential"]
print(len(residential), "residential polygons")
print(residential["name"].dropna().head().tolist())
159 residential polygons
['Wing', 'Cottesmore Hall Redevelopment', "Permanent Traveller's Camp", 'Manor Farm', 'Lonsdale Park']

You can also remove rows with missing or empty geometry:

with_geometry = landuse[landuse.geometry.notna() & ~landuse.geometry.is_empty]
print(len(landuse) - len(with_geometry), "rows dropped")
0 rows dropped

None here; what null, empty and invalid geometry are, and why they differ, is in null, empty and invalid geometry.

Check geometry types

print(landuse.geom_type.value_counts())
print(wards.geom_type.value_counts())
Polygon         2401
MultiPolygon       4
Name: count, dtype: int64
Polygon    15
Name: count, dtype: int64

Four land-use areas are drawn in more than one piece and come back as MultiPolygon; a shapefile does not distinguish the two, so a polygon layer is often a mix. That is normal. Points or lines in a polygon layer are not.

Plot the data for a quick visual check

A plot is the fastest check that the layer is where it should be:

residential.plot()

For a slightly clearer result, draw the wards underneath so you can see whether the filtered features land where you expect:

ax = wards.plot(figsize=(8, 8), color="white", edgecolor="grey")
residential.plot(ax=ax, color="tab:red")
ax.set_title("Residential land use in Rutland")

A layer in the wrong CRS shows up at once: it lands far away from the other one, or the axes read in hundreds of thousands instead of degrees. Making the map presentable is plotting maps with GeoPandas and Matplotlib.

Save the result to a new file

Save to GeoJSON

residential.to_file("output/residential.geojson", driver="GeoJSON")

Save to a shapefile or GeoPackage

residential.to_file("output/residential.shp")
residential.to_file("output/rutland.gpkg", layer="residential")

import os
shp = sorted(f for f in os.listdir("output") if f.startswith("residential.") and not f.endswith((".geojson", ".png")))
print(shp, f"{sum(os.path.getsize('output/' + f) for f in shp) / 1e3:.1f} kB")
print(f"residential.geojson {os.path.getsize('output/residential.geojson') / 1e3:.1f} kB")
print(f"rutland.gpkg        {os.path.getsize('output/rutland.gpkg') / 1e3:.1f} kB")
['residential.cpg', 'residential.dbf', 'residential.prj', 'residential.shp', 'residential.shx'] 138.8 kB
residential.geojson 181.6 kB
rutland.gpkg        225.3 kB

One shapefile write is five files. The .dbf holds each of the three text fields at 80 characters, 250 bytes a row however short the names; a one-feature GeoPackage of this layer was already 98.3 kB, the cost of its tables and index. GIS file formats compared goes further.

The 159 Rutland residential polygons written three ways: shapefile, GeoJSON and GeoPackage. the same 159 polygons, written three waysShapefileGeoJSONGeoPackageon disk5 files1 text file1 SQLite filesize138.8 kB181.6 kB225.3 kBwatch fornames cut at 10text coordinates~98 kB overheadMeasured on this layer; each format grows differently spatialworkflow.io
The same 159 polygons written three ways. The GeoPackage is largest here only because of its fixed overhead of about 98 kB.

The extract measured against Rutland's wards

The data used on this page

The extract is Geofabrik's Rutland shapefile download of 1 January 2026 (Β© OpenStreetMap contributors, ODbL), so the counts stay put; the boundary that it is measured against is the county's 15 wards from the ONS December 2024 boundaries (OGL).

import io
import os
import zipfile

import geopandas as gpd
import pandas as pd
import requests

pd.set_option("display.width", 120)       # print whole rows instead of eliding columns
pd.set_option("display.max_columns", None)
pd.set_option("display.max_colwidth", 40)
os.makedirs("data/rutland", exist_ok=True)
os.makedirs("output", exist_ok=True)

if not os.path.exists("data/rutland/gis_osm_landuse_a_free_1.shp"):
    extract = requests.get("https://download.geofabrik.de/europe/united-kingdom/england/"
                           "rutland-260101-free.shp.zip", timeout=300)
    extract.raise_for_status()
    zipfile.ZipFile(io.BytesIO(extract.content)).extractall("data/rutland")

if not os.path.exists("data/rutland_wards.geojson"):
    wards = requests.get("https://services1.arcgis.com/ESMARspQHYMw9BZ9/arcgis/rest/services/"
                         "Wards_December_2024_Boundaries_UK_BGC/FeatureServer/0/query",
                         params={"where": "LAD24NM='Rutland'", "outFields": "WD24CD,WD24NM",
                                 "outSR": 4326, "f": "geojson"}, timeout=120)
    wards.raise_for_status()
    open("data/rutland_wards.geojson", "wb").write(wards.content)

print(len([f for f in os.listdir("data/rutland") if f.endswith(".shp")]), "shapefiles in the extract")
18 shapefiles in the extract

The extract holds a shapefile per theme β€” roads, buildings, water, places and so on. This page reads only the land-use one.

Example 1: How much of the "Rutland" extract is in Rutland

Dissolve the 15 wards into the county and measure how much of each land-use polygon falls inside it, in British National Grid so the areas are hectares:

import geopandas as gpd

landuse = gpd.read_file("data/rutland/gis_osm_landuse_a_free_1.shp").to_crs(27700)
wards = gpd.read_file("data/rutland_wards.geojson").to_crs(27700)
county = wards.dissolve().geometry.iloc[0]

landuse["ha"] = landuse.area / 1e4
landuse["ha_in_rutland"] = landuse.intersection(county).area / 1e4
total, inside = landuse["ha"].sum(), landuse["ha_in_rutland"].sum()
print(f"{total:,.0f} ha in the extract, {inside:,.0f} ha in Rutland: {total - inside:,.0f} ha ({1 - inside / total:.1%}) outside")

outside = landuse[landuse["ha_in_rutland"] < landuse["ha"] / 2]
print(len(outside), "polygons lie mostly outside; the largest residential one:")
big = outside[outside["fclass"] == "residential"].nlargest(1, "ha")
print(big[["osm_id", "ha", "ha_in_rutland"]].round(1).to_string(index=False),
      "| centroid lon/lat", *[round(c, 3) for c in big.centroid.to_crs(4326).iloc[0].coords[0]])
26,893 ha in the extract, 24,307 ha in Rutland: 2,586 ha (9.6%) outside
169 polygons lie mostly outside; the largest residential one:
   osm_id    ha  ha_in_rutland
521191913 398.5            3.3 | centroid lon/lat -0.489 52.657

A tenth of the extract β€” 2,586 ha in 169 polygons that lie mostly over the border β€” is not in Rutland. The largest residential polygon among them, OpenStreetMap way 521191913, is 398.5 ha with 3.3 ha on the Rutland side, and its centroid at 0.489Β° W, 52.657Β° N is Stamford, in Lincolnshire. It is a quarter of the 1,594 ha that fclass == "residential" selects.

Map of Rutland's ward boundary with the land use of Geofabrik's Rutland extract: almost all of it inside the county, and 2,586 hectares in patches over the border, the largest being Stamford's housing on the eastern edge. Map of Rutland's ward boundary with the land use of Geofabrik's Rutland extract: almost all of it inside the county, and 2,586 hectares in patches over the border, the largest being Stamford's housing on the eastern edge.
Geofabrik's Rutland extract reaches over the county boundary on every side. A filter for residential land picks up Stamford, in Lincolnshire.

Example 2: Residential land per ward

With the county cut out, overlay splits each residential polygon along the ward boundaries, so a polygon that spans two wards contributes its part to each:

import pandas as pd

residential = landuse[landuse["fclass"] == "residential"]
pieces = gpd.overlay(residential[["osm_id", "geometry"]], wards[["WD24NM", "geometry"]], how="intersection")
per_ward = (pieces.area / 1e4).groupby(pieces["WD24NM"]).sum()
ward_ha = wards.set_index("WD24NM").area / 1e4

table = pd.DataFrame({"residential_ha": per_ward, "share_of_ward": per_ward / ward_ha}).rename_axis(None)
print(table.sort_values("share_of_ward", ascending=False).to_string(
    formatters={"residential_ha": "{:,.1f}".format, "share_of_ward": "{:.1%}".format}))
print(f"{residential['ha'].sum():,.0f} ha in the filter, {per_ward.sum():,.0f} ha inside the wards, "
      f"{len(pieces)} pieces from {pieces['osm_id'].nunique()} polygons")
                          residential_ha share_of_ward
Oakham North East                   42.1         32.4%
Oakham South                       109.6         27.2%
Uppingham                           97.2         12.5%
Oakham North West                   44.3         11.8%
Barleythorpe                        29.0          7.2%
Ketton                             141.8          4.5%
Langham                             52.8          4.5%
Cottesmore                          64.7          3.0%
Ryhall & Casterton                 101.2          2.8%
Normanton                          104.8          2.4%
Whissendine                         47.6          2.2%
Lyddington                          69.9          2.0%
Greetham                            75.4          1.8%
Braunston & Martinsthorpe          120.4          1.7%
Exton                               66.5          1.1%
1,594 ha in the filter, 1,167 ha inside the wards, 168 pieces from 153 polygons

Inside the wards there are 1,167 ha of mapped residential land, not the 1,594 ha the attribute filter alone returns. 153 of the 159 polygons reach a ward at all, and cutting them along ward lines gives 168 pieces β€” the 15 extra come from polygons that straddle a boundary, which a plain spatial join would have counted whole in both wards. Oakham's wards are the most built-up, Oakham North East at 32.4% residential and Oakham South at 27.2%; Ketton has the most residential land in hectares, 141.8, but in a ward large enough that it is 4.5% of it.

Why a county extract is not the county

Geofabrik cuts each extract out of the planet file along a polygon of its own, and keeps whole any feature that crosses the cut. Stamford's residential polygon has 3.3 of its 398.5 ha in Rutland, so all of it came in. Other polygons in the extract have none of their area inside the county at all, so the cut line itself runs outside the boundary: Geofabrik publishes it as a .poly file beside each download.

That is a sensible way to cut a map β€” a road that leaves the county and comes back should not be broken in two β€” but it means a regional extract is the area and some of its surroundings, not an administrative unit. Counts, areas and totals from it describe the extract. To describe the county, cut the data with the county's own boundary first, as Example 1 measures and Example 2 does.

Missing labels and big files

CRS missing, field names cut short

Copy a shapefile without its .prj and it reads with no CRS; label it only from what the source documents (cannot transform naive geometries). Write a column called area_hectares to a shapefile and it comes back as area_hecta, because the format allows ten characters (shapefile column names truncated).

Large files can be slow

Large parcel or boundary datasets may load slowly and be expensive to plot. You do not have to read a whole file to see what is in it β€” pyogrio.read_info() reports the count, CRS and fields without loading the features, and rows= reads just the first few:

import pyogrio

info = pyogrio.read_info("data/rutland/gis_osm_buildings_a_free_1.shp")
print(info["features"], "features;", info["crs"], ";", list(info["fields"]))
print(gpd.read_file("data/rutland/gis_osm_buildings_a_free_1.shp", rows=3)[["osm_id", "fclass"]])
5513 features; EPSG:4326 ; ['osm_id', 'code', 'fclass', 'name', 'type']
     osm_id    fclass
0   3700606  building
1   3700607  building
2  59833301  building

read_file() also takes columns= to skip fields and bbox= or mask= to read only the features in an area.