1  Geographic data in Python

1.1 Introduction

This chapter outlines two fundamental geographic data models — vector and raster — and introduces the main Python packages for working with them. Before demonstrating their implementation in Python, we will introduce the theory behind each data model and the disciplines in which they predominate.

The vector data model (Section 1.2) represents the world using points, lines, and polygons. These have discrete, well-defined borders, meaning that vector datasets usually have a high level of precision (but not necessarily accuracy). The raster data model (Section 1.3), on the other hand, divides the surface up into cells of constant size. Raster datasets are the basis of background images used in web-mapping and have been a vital source of geographic data since the origins of aerial photography and satellite-based remote sensing devices. Rasters aggregate spatially specific features to a given resolution, meaning that they are consistent over space and scalable, with many worldwide raster datasets available.

Which to use? The answer likely depends on your domain of application, and the datasets you have access to:

  • Vector datasets and methods dominate the social sciences because human settlements and and processes (e.g., transport infrastructure) tend to have discrete borders
  • Raster datasets and methods dominate many environmental sciences because of the reliance on remote sensing data

Python has strong support for both data models. We will focus on shapely and geopandas for working with geograpic vector data, and rasterio for working with rasters.

shapely is a “low-level” package for working with individual vector geometry objects. geopandas is a “high-level” package for working with geometry columns (GeoSeries objects), which internally contain shapely geometries, and vector layers (GeoDataFrame objects). The geopandas ecosystem provides a comprehensive approach for working with vector layers in Python, with many packages building on it.

There are several partially overlapping packages for working with raster data, each with its own advantages and disadvantages. In this book, we focus on the most prominent one: rasterio, which represents “simple” raster datasets with a combination of a numpy array, and a metadata object (dict) providing geographic metadata such as the coordinate system. xarray is a notable alternative to rasterio not covered in this book which uses native xarray.Dataset and xarray.DataArray classes to effectively represent complex raster datasets such as ‘NetCDF’ files with multiple bands and metadata.

There is much overlap in some fields and raster and vector datasets can be used together: ecologists and demographers, for example, commonly use both vector and raster data. Furthermore, it is possible to convert between the two forms (see Chapter 5). Whether your work involves more use of vector or raster datasets, it is worth understanding the underlying data models before using them, as discussed in subsequent chapters.

1.2 Vector data

The geographic vector data model is based on points located within a coordinate reference system (CRS). Points can represent self-standing features (e.g., the location of a bus stop), or they can be linked together to form more complex geometries such as lines and polygons. Most point geometries contain only two dimensions (3-dimensional CRSs may contain an additional \(z\) value, typically representing height above sea level).

In this system, London, for example, can be represented by the coordinates (-0.1,51.5). This means that its location is -0.1 degrees east and 51.5 degrees north of the origin. The origin, in this case, is at 0 degrees longitude (a prime meridian located at Greenwich) and 0 degrees latitude (the Equator) in a geographic (‘lon/lat’) CRS (Figure 1.1, left panel). The same point could also be approximated in a projected CRS with ‘Easting/Northing’ values of (530000, 180000) in the British National Grid, meaning that London is located 530 \(km\) East and 180 \(km\) North of the origin of the CRS (Figure 1.1, right panel). The location of National Grid’s origin, in the sea beyond South West Peninsular, ensures that most locations in the UK have positive Easting and Northing values.

Figure 1.1: Illustration of vector (point) data in which location of London (the red X) is represented with reference to an origin (the blue circle). The left plot represents a geographic CRS with an origin at 0° longitude and latitude. The right plot represents a projected CRS with an origin located in the sea west of the South West Peninsula.

There is more to CRSs, as described in Section 1.4 and Chapter 6 but, for the purposes of this section, it is sufficient to know that coordinates consist of two numbers representing the distance from an origin, usually in \(x\) then \(y\) dimensions.

geopandas (Bossche et al. 2023) provides classes for geographic vector data and a consistent command-line interface for reproducible geographic data analysis in Python. It also provides an interface to three mature libraries for geocomputation which, in combination, represent a strong foundation on which many geographic applications (including QGIS and R’s spatial ecosystem):

  • GDAL, for reading, writing, and manipulating a wide range of geographic data formats, covered in Chapter 7
  • PROJ, a powerful library for coordinate system transformations, which underlies the content covered in Chapter 6
  • GEOS, a planar geometry engine for operations such as calculating buffers and centroids on data with a projected CRS, covered in Chapter 4

Tight integration with these geographic libraries makes reproducible geocomputation possible: an advantage of using a higher level language such as Python to access these libraries is that you do not need to know the intricacies of the low level components, enabling focus on the methods rather than the implementation.

1.2.1 Vector data classes

The main classes for working with geographic vector data in Python are hierarchical, meaning the highest level ‘vector layer’ class is composed of simpler ‘geometry column’ and individual ‘geometry’ components. This section introduces them in order, starting with the highest level class. For many applications, the high level vector layer class, which are essentially a data frame with geometry columns, are all that’s needed. However, it’s important to understand the structure of vector geographic objects and their component pieces for more advanced applications. The three main vector geographic data classes in Python are:

  • GeoDataFrame, a class representing vector layers, with a geometry column (class GeoSeries) as one of the columns
  • GeoSeries, a class that is used to represent the geometry column in GeoDataFrame objects
  • shapely geometry objects which represent individual geometries, such as a point or a polygon

The first two classes (GeoDataFrame and GeoSeries) are defined in geopandas. The third class is defined in the shapely package, which deals with individual geometries, and is a main dependency of the geopandas package.

1.2.2 Vector layers

The most commonly used geographic vector data structure is the vector layer. There are several approaches for working with vector layers in Python, ranging from low-level packages (e.g., osgeo, fiona) to the relatively high-level geopandas package that is the focus of this section. Before writing and running code for creating and working with geographic vector objects, we need to import geopandas (by convention as gpd for more concise code) and shapely.

import pandas as pd
import shapely
import geopandas as gpd

We also limit the maximum number of printed rows to six, to save space, using the 'display.max_rows' option of pandas.

pd.set_option('display.max_rows', 6)

Projects often start by importing an existing vector layer saved as a GeoPackage (.gpkg) file, an ESRI Shapefile (.shp), or other geographic file format. The function read_file() imports a GeoPackage file named world.gpkg located in the data directory of Python’s working directory into a GeoDataFrame named gdf.

gdf = gpd.read_file('data/world.gpkg')

The result is an object of type (class) GeoDataFrame with 177 rows (features) and 11 columns, as shown in the output of the following code:

(177, 11)

The GeoDataFrame class is an extension of the DataFrame class from the popular pandas package (McKinney 2010). This means we can treat non-spatial attributes from a vector layer as a table, and process them using the ordinary, i.e., non-spatial, established function methods. For example, standard data frame subsetting methods can be used. The code below creates a subset of the gdf dataset containing only the country name and the geometry.

gdf = gdf[['name_long', 'geometry']]
name_long geometry
1 Tanzania MULTIPOLY...
2 Western S... MULTIPOLY...
... ... ...
174 Kosovo MULTIPOLY...
175 Trinidad ... MULTIPOLY...
176 South Sudan MULTIPOLY...

177 rows × 2 columns

The following expression creates a subdataset based on a condition, such as equality of the value in the 'name_long' column to the string 'Egypt'.

gdf[gdf['name_long'] == 'Egypt']
name_long geometry
163 Egypt MULTIPOLY...

Finally, to get a sense of the spatial component of the vector layer, it can be plotted using the .plot method (Figure 1.2).

Figure 1.2: Basic plot of a GeoDataFrame

Interactive maps of GeoDataFrame objects can be created with the .explore method, as illustrated in Figure 1.3 which was created with the following command:

Make this Notebook Trusted to load map: File -> Trust Notebook
Figure 1.3: Basic interactive map with .explore

A subset of the data can be also plotted in a similar fashion.

gdf[gdf['name_long'] == 'Egypt'].explore()
Make this Notebook Trusted to load map: File -> Trust Notebook
Figure 1.4: Interactive map of a GeoDataFrame subset

1.2.3 Geometry columns

The geometry column of class GeoSeries is an essential column in a GeoDataFrame. It contains the geometric part of the vector layer, and is the basis for all spatial operations. This column can be accessed by name, which typically (e.g., when reading from a file) is 'geometry', as in gdf['geometry']. However, the recommendation is to use the fixed .geometry property, which refers to the geometry column regardless whether its name is 'geometry' or not. In the case of the gdf object, the geometry column contains 'MultiPolygon's associated with each country.

0      MULTIPOLY...
1      MULTIPOLY...
2      MULTIPOLY...
174    MULTIPOLY...
175    MULTIPOLY...
176    MULTIPOLY...
Name: geometry, Length: 177, dtype: geometry

The geometry column also contains the spatial reference information, if any (also accessible with the shortcut gdf.crs).

<Geographic 2D CRS: EPSG:4326>
Name: WGS 84
Axis Info [ellipsoidal]:
- Lat[north]: Geodetic latitude (degree)
- Lon[east]: Geodetic longitude (degree)
Area of Use:
- name: World.
- bounds: (-180.0, -90.0, 180.0, 90.0)
Datum: World Geodetic System 1984 ensemble
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich

Many geometry operations, such as calculating the centroid, buffer, or bounding box of each feature involve just the geometry. Applying this type of operation on a GeoDataFrame is therefore basically a shortcut to applying it on the GeoSeries object in the geometry column. For example, the two following commands return exactly the same result, a GeoSeries with country bounding box polygons (using the .envelope method).

0      POLYGON (...
1      POLYGON (...
2      POLYGON (...
174    POLYGON (...
175    POLYGON (...
176    POLYGON (...
Length: 177, dtype: geometry
0      POLYGON (...
1      POLYGON (...
2      POLYGON (...
174    POLYGON (...
175    POLYGON (...
176    POLYGON (...
Length: 177, dtype: geometry

Note that .envelope, and other similar operators in geopandas such as .centroid (Section 4.2.2), .buffer (Section 4.2.3) or .convex_hull, return only the geometry (i.e., a GeoSeries), not a GeoDataFrame with the original attribute data. In case we want the latter, we can create a copy of the GeoDataFrame and then “overwrite” its geometry (or, we can overwrite the geometries directly in case we do not need the original ones, as in gdf.geometry=gdf.envelope).

gdf2 = gdf.copy()
gdf2.geometry = gdf.envelope
name_long geometry
0 Fiji POLYGON (...
1 Tanzania POLYGON (...
2 Western S... POLYGON (...
... ... ...
174 Kosovo POLYGON (...
175 Trinidad ... POLYGON (...
176 South Sudan POLYGON (...

177 rows × 2 columns

Another useful property of the geometry column is the geometry type, as shown in the following code. Note that the types of geometries contained in a geometry column (and, thus, a vector layer) are not necessarily the same for every row. Accordingly, the .type property returns a Series (of type string), rather than a single value (the same can be done with the shortcut gdf.geom_type).

0      MultiPolygon
1      MultiPolygon
2      MultiPolygon
174    MultiPolygon
175    MultiPolygon
176    MultiPolygon
Length: 177, dtype: object

To summarize the occurrence of different geometry types in a geometry column, we can use the pandas method called value_counts.

MultiPolygon    177
Name: count, dtype: int64

It is possible to have multiple geometry types in a single GeoSeries. However, in this case, we see that the gdf layer contains only 'MultiPolygon' geometries.

A GeoDataFrame can also have multiple GeoSeries.

gdf['bbox'] = gdf.envelope
gdf['polygon'] = gdf.geometry

Only one geometry column at a time is “active”, in the sense that it is being accessed in operations involving the geometries (such as .centroid, .crs, etc.). To switch the active geometry column from one GeoSeries column to another, we use set_geometry. Figure 1.5 and Figure 1.6 shows interactive maps of the gdf layer with the 'bbox' and 'polygon' geometry columns activated, respectively.

gdf = gdf.set_geometry('bbox')
Make this Notebook Trusted to load map: File -> Trust Notebook
Figure 1.5: Switching to the 'bbox' geometry column in the world layer, and plotting it
gdf = gdf.set_geometry('polygon')
Make this Notebook Trusted to load map: File -> Trust Notebook