Mapping Census Data with Python

Python
Census
GeoPandas
Kentucky
Louisville
Internet
A tutorial on how to make maps by pulling Census data into Python
Published

March 26, 2023

This post covers two useful skils, making maps and accessing Census data. Most of the python map making tutorials I found online showed how to make maps using data that already came with the library, and didn’t have many notes on how the data is formatted or how to bring in new data.

In addition to the standard analysis libraries numpy and pandas, we’re going to use GeoPandas for mapping data and the requests library for getting Census data

import numpy as np
import pandas as pd
import geopandas as gpd
import requests

The Initial Map Layer

The census has shapefiles here and I’ve downloaded a zip file of all counties in the United States. I’ll filter it down to just Kentucky for this example.

GeoPandas works well with census shapefiles out of the box. Don’t unzip the downloaded file, it can be read straight into a GeoPandas dataframe, which resembles a pandas dataframe, but with an additional column of geographic attributes.

county_shp = gpd.read_file('cb_2021_us_county_500k.zip')
ky_counties = county_shp[county_shp.STATE_NAME == 'Kentucky']

Geopandas also provides built-in integrations with both matplotlib (for static maps) and folium (for interactive maps). Folium is a python wrapper for leaflet, which produces interactive maps. Producing the initial map layer is straightforward using the built in explore method.

ky_counties.explore()
Make this Notebook Trusted to load map: File -> Trust Notebook