Case study
A Python tool that turns raw Census tables into mapped shapefiles and reports
An ArcMap script tool, written in Python, that cleans a 2010 Census CSV, filters it by county and gender, joins it to tract boundaries, and produces a map and an HTML summary report.
- Context
- Programming course project (GIS 540), NC State, fall 2016. The tool’s requirements were set by the assignment
- Data
- 2010 Census age and sex counts by tract (CSV) and NC boundary shapefile, provided with the assignment
- Output
- Cleaned CSVs, a shapefile, a map image and an HTML report, from one button in ArcMap
Problem
The assignment described a workflow that was being done by hand: Census CSV files could not be joined to map data in ArcGIS because the field names were in the second row, contained spaces and special characters, and were too long. The task was to write a tool that fixes the file, filters it, joins it to the map, and reports summary statistics automatically.
Approach
I wrote the tool in Python with arcpy and connected it to an ArcMap toolbar button through a script tool form. The user picks the CSV, a gender (female, male or total), a county, an output name, the boundary shapefile and a map document. The script then:
- Reads the raw CSV with plain file input and output, drops the extra header row, and rewrites long Census field names into short ArcGIS-safe names. For example, “Number; SEX AND AGE - Male population - 80 to 84 years” becomes
MPop80_84. It also extracts the county name into its own field, and saves a full cleaned CSV. - Writes a second CSV containing only the selected county’s rows and the selected gender’s columns.
- Joins that table to the tract boundaries (Make Feature Layer, Add Join, Copy Features) to create a new shapefile, and adds it to the open map.
- Exports the map to an image, and calculates total, minimum and maximum population and average age with a statistics class built on search cursors.
- Writes an HTML report with the statistics and the map image, and opens it in the browser. Progress messages report each step in ArcMap.
I saved 15 versions of the script while building it up step by step. Credit where it is due: two helper functions (finding a field’s position in a line, and printing messages) come from Dr. Laura Tateosian’s book Python for ArcGIS, and the course TA helped me work out the column filtering. Both are credited in the code.
Result
A working one-button tool. Below are example outputs from my project files: a map with the selected county highlighted, and the filtered female-population table for Harnett County.