Skip to content

Download the Jupyter notebook

Introduction to Python and Geopandas

BIO597 Spatial Analysis of Biodiversity Fall 2026

Goals for today

This notebook is intended to introduce you to the basic workflow of using Python within Jupyter notebooks, using geopandas and species occurrence data as the motivating examples.

Here are some basic expectations for labs/assignments: * I do not expect you to be python/programming experts coming into this class * We will introduce and reinforce programming concepts gradually

What are Jupyter Notebooks and why would I want to use one?

Jupyter notebooks are a great way to generate reproducible scientific analysis workflows in python. You can mix documentation, code, tables, and figures in one executable document which can easily be shared and published to the web. It's very common to organize/share notebooks in github. Here is a good example of a notebook demonstrating a method I am developing called Multispecies EstimAtion of Dispersal On netWorks (Meadow).

Let's get started.

#### This is your first markdown cell

Try running this cell by pressing the 'play' button in the toolbar above. What happens?

Markdown cells contain formatted text instead of Python code. They are useful for notes, explanations, headings, links, and instructions.
# This is your first actual code cell.

# python uses the pound sign ('#') to indicate a comment line (lines that will be ignored when running the code).

# Imports
# It's very standard to have the first code cell in a notebook import any needed packages

# Here we import geopandas, a simple python geospatial analysis package. 
# Saying 'as gpd' creates a synonym, so we can call
# functions from this package using the shorter name (saves typing).
import geopandas as gpd
# We also import the standard pandas python library for manipulating tabular data
import pandas as pd

Species occurrence records

Data for this exercise is from Harrington et al 2024 "Pleistocene Glaciation Drove Shared Population Coexpansion in Eastern North American Snakes"

The EasternSnakes folder contains simple CSV files of occurrence records for several snake species. Each row is one record, with an ID, Longitude, and Latitude.

A CSV is just a table, so we will first read it with pandas, then convert it to a GeoDataFrame by turning the longitude and latitude columns into point geometries.

sdekayi_csv = "EasternSnakes/Sdekayi_coords.csv"
sdekayi_df = gpd.read_file(sdekayi_csv)
sdekayi_df.head()

Convert the table to a GeoDataFrame

We will start with DeKay's brownsnake (Storeria dekayi). The important step is points_from_xy, which creates point geometries from the longitude and latitude columns.

The coordinate reference system, or CRS, is EPSG:4326 because these coordinates are longitude and latitude in decimal degrees. We will talk more about CRS later in the exercise and throughout the course.

sdekayi_gdf = gpd.GeoDataFrame(
    sdekayi_df,
    geometry=gpd.points_from_xy(sdekayi_df["Longitude"], sdekayi_df["Latitude"]),
    crs="EPSG:4326",
)

sdekayi_gdf["Species"] = "Storeria dekayi"

sdekayi_gdf.head()

Plot the first species

geopandas geodataframes have a very useful function called explore() to plot the geometries on an interactive map. At this stage, we are mainly checking that the coordinates were read correctly and appear in a reasonable part of eastern North America.

sdekayi_gdf.explore()

Load and plot a second species

Now repeat the same workflow for eastern copperhead (Agkistrodon contortrix). Repeating the steps once by hand is useful practice before wrapping the workflow in a function.

acontortrix_csv = "EasternSnakes/Acontortrix_coords.csv"
acontortrix_df = gpd.read_file(acontortrix_csv)

acontortrix_gdf = gpd.GeoDataFrame(
    acontortrix_df,
    geometry=gpd.points_from_xy(acontortrix_df["Longitude"], acontortrix_df["Latitude"]),
    crs="EPSG:4326",
)
acontortrix_gdf["Species"] = "Agkistrodon contortrix"

acontortrix_gdf.head()
acontortrix_gdf.explore()

Merge the two GeoDataFrames

Because both species tables have the same columns and the same CRS, we can stack them into one combined GeoDataFrame with pd.concat. Keeping a Species column lets us separate the records again later.

snakes_gdf = pd.concat([sdekayi_gdf, acontortrix_gdf])
snakes_gdf.explore()

Color points by labels in a column

The previous figure shows the sampling distribution of both species combined, but it uses the same color for all points, which isn't very useful. We can tell gdf.explore() which column we are interested in for differentiating points by passing in the species ID column.

snakes_gdf.explore(column="Species")

Choosing a color scheme

geopandas picks a default color scheme which sometimes works, and sometimes not. Here it didn't work so well because the light blue of Storeria dekayi is somewhat difficult to see. You can set your own colormap with the cmap parameter. Let's choose rainbow which gives nice results for 2 species.

You can see all the available colormaps in the python colormap reference

snakes_gdf.explore(column="Species", cmap="rainbow")

A few basic spatial analyses

Once the records are in one GeoDataFrame, we can ask simple spatial questions. The examples below are intentionally basic: count records, draw a simple hull around the occurrence records for each species, estimate the total geographic area of each species.

For area e calculations, we first project the data from longitude/latitude into EPSG:5070, a projected CRS for North America with units in meters. Areas and distances in decimal degrees are hard to interpret, so this projection step matters.

# Count occurrence records for each species.
record_counts = snakes_gdf.groupby("Species").size()
record_counts
# Project the combined records before measuring areas.
snakes_projected = snakes_gdf.to_crs("EPSG:5070")
snakes_projected.crs
# Draw a simple convex hull around the records for each species.
# A convex hull is the smallest convex polygon that contains all points.
hulls_projected = snakes_projected.dissolve(by="Species").reset_index()

hulls_projected["geometry"] = hulls_projected.geometry.convex_hull

hulls = hulls_projected.to_crs(snakes_gdf.crs)

hulls.explore(column="Species", cmap="rainbow")

Calculate the total area of the convex hull for each species

Geopandas polygons have an area property that is measured in square meters, so we can convert this to square kilometers by dividing by 1,000,000

hulls["convex_hull_area_km2"] = hulls_projected.area / 1000000
hulls

Practice submitting your work to your github

Now that you have run through this exercise, practice submitting your notebook code to your class repo.

Open a terminal window and run these commands to add, commit, and push your notebook:

```

Go to the labs directory in the course repo

cd ~/BIO597-SpatialBiodiversity/docs/labs

Add your changed lab

git add Lab01-IntroPython-Geopandas.ipynb git commit -m 'Finished Lab01' git push