Spatial Analysis with Python: GeoPandas Basics

In short
- A GeoDataFrame is a table that carries spatial location information, like a spreadsheet with a map attached.
- Reading files, converting coordinates and running a spatial join take about ten lines of code.
- A code-based approach is especially powerful for disaster field data that needs repeated analysis.
Imagine you receive a shelter location file and a flood zone file at a flood site, and you need to find out which shelters are inside the flood zone. In QGIS, you load the two layers, find the Vector > Data Management Tools > Join Attributes by Location menu, set it up and save. Doing that once is fine. But what if you must repeat it in the same way with a flood zone file that is updated every day through the typhoon season?
The GeoPandas library for Python (a tool that adds geometry information to the Pandas table structure so you can work with spatial data) lets you fix that workflow in code and run it again by changing only the file. This post explains what a GeoDataFrame is, and walks through reading files, changing the coordinate system and linking two layers spatially, with short code. It also covers what changes when you move work from a spreadsheet or QGIS into code.
How is a GeoDataFrame different from an ordinary table?
A pandas DataFrame is a table of rows and columns. A GeoDataFrame is that table with one added geometry column. This column holds spatial shapes such as points, lines and polygons, and each row has one spatial object together with its attribute values. It is similar to a spreadsheet with map pin information attached as one extra column.
An important difference is that a GeoDataFrame remembers its own CRS (coordinate reference system) information. It stores the reference used to express positions, such as EPSG:4326 (longitude and latitude) and EPSG:5186 (Korean metric coordinates) covered in the previous post on coordinate systems. If you simply merge two files with different coordinate systems, positions can be off by hundreds of kilometers. GeoPandas is designed to handle the CRS explicitly, which helps catch this kind of mistake early. In disaster response, files received from different agencies often use different coordinate systems.
How do you read a shapefile or GeoJSON?
The basic function for reading a file in GeoPandas is gpd.read_file(). It reads common spatial file formats such as Shapefile (.shp), GeoJSON (.geojson) and GeoPackage (.gpkg) without a separate conversion.
import geopandas as gpd
# Read shelter point data
shelter = gpd.read_file("shelter.geojson")
# Read flood zone polygons
flood = gpd.read_file("flood_zone.shp")
# Check the coordinate systems
print(shelter.crs) # e.g. EPSG:4326
print(flood.crs) # e.g. EPSG:5186
The first thing to do after reading files is to print the .crs attribute and check whether the two files use the same coordinate system. This is the first gate in what you only learn by running it. If the outputs differ, you must unify them before any spatial operation. In practice, open data from different agencies can use different coordinate systems, so make a habit of checking the CRS first whenever you receive data.
Which function changes the coordinate system?
A single method, .to_crs(), handles coordinate conversion. Distance and area calculations and spatial joins work correctly only when both layers are in the same coordinate system.
# Match shelter to the coordinate system of flood
shelter_proj = shelter.to_crs(flood.crs)
# Or specify it directly by EPSG code
shelter_proj = shelter.to_crs(epsg=5186)
Note that .to_crs() does not modify the original; it returns a new GeoDataFrame. To avoid overwriting the original variable, assign the result to a new variable. If you convert to a coordinate system in meters (for example, EPSG:5186), distances and areas you calculate later come out in meters, which makes the results much easier to interpret. For example, when you extract homes within 500 meters of a landslide risk zone, a coordinate system that is not in meters forces you to express the buffer radius as a difference in longitude and latitude, which invites mistakes.
When do you use a spatial join?
A spatial join combines two layers based on their spatial relationship. You use it to link attributes by a spatial containment relationship, such as "is this point inside that polygon?" In QGIS, the Vector > Data Management Tools > Join Attributes by Location menu does the same job.
# Find shelters inside the flood zone
joined = gpd.sjoin(shelter_proj, flood, how="inner", predicate="within")
print(joined[["name", "flood_level"]])
For the predicate option, you pick from "within" (contained inside the polygon), "intersects" (intersecting, including the boundary), "contains" and others, depending on the situation. how="inner" keeps only rows that meet the condition, while "left" keeps every row of the left layer and attaches values only where they match. When you design a wildfire evacuation route, joining road lines with risk zone polygons under the intersects condition can automatically pick out the road sections that pass through the risk zone.
Is there a reason to move work from a spreadsheet or QGIS into code?
Clicking through QGIS menus and running code give the same result. The difference lies in repeatability and record keeping. With code, you can run yesterday's analysis again today by changing only the file name, and the coordinate system you converted to and the condition you joined on are recorded in the code itself, so it is easy to share with a colleague or review six months later. You can imitate a spatial join with a spreadsheet VLOOKUP, but spreadsheets do not support location-based relationships by default, so manual work creeps in along the way.
Some things you only learn by doing. Run the same analysis once with QGIS menus and once with GeoPandas code, and compare whether the number of rows and the attribute values in the result layers match. If they match, that confirms the code works correctly; if they differ, suspect the predicate option or a coordinate system mismatch. This habit of verification directly raises the reliability of the numbers that go into disaster response reports. Menu names and function argument names can differ between versions, so keep the API reference of the official GeoPandas documentation (geopandas.org) open alongside.
Step by step on screen
The figure below is a diagram that summarizes the order of the steps.

- Prepare the environment
Type pip install geopandas in a terminal and confirm the installation-complete message - Read a file
In a Jupyter notebook or VS Code, run gpd.read_file("path/to/file.shp") - Check the CRS
Print shelter.crs and flood.crs and compare the two values by eye - Convert coordinates
Enter shelter_proj = shelter.to_crs(flood.crs), then check shelter_proj.crs again - Spatial join
Run gpd.sjoin(shelter_proj, flood, how="inner", predicate="within") - Review the result
Check the number of rows with joined.shape, and visualize the result on a map with joined.explore()
Menu names may differ slightly between program versions.
Prompts you can copy
Use this to paste in a GeoPandas error message and get the cause and a fix
I am a beginner studying GeoPandas in Python. Read the error message and code below and explain the cause in English. Explain it at a level a middle school student can understand, and add a short explanation in parentheses when a technical term appears. Also show the corrected code, with a comment on each line saying what it does. Do not use functions or parameters that you made up or that do not exist. [Paste the error message here] [Paste the code that caused the problem here] Items to check: confirm yourself that the function names and parameters the AI suggests really exist in the official GeoPandas documentation.
Use this to organize a disaster response data analysis scenario as a code flow
I want to do [analysis goal, e.g. identify shelters inside the flood zone] for a [target disaster, e.g. flood] situation using GeoPandas. The files I will use are [description of file 1] and [description of file 2]. Answer in the order below. 1) Preprocessing steps needed, 2) How to check and convert the coordinate system, 3) A spatial join code example, 4) How to verify the result. Include code of 10 lines or fewer in each step, and clearly mark any assumptions. Mark anything uncertain as "needs checking". Items to check: confirm that the EPSG code it suggests really fits your data, and that the file paths and column names match your actual data.
Replace the bracketed parts for your situation. Check the facts in any answer before you use it.
Try it yourself
- On the Korean Public Data Portal (data.go.kr), search for "shelter" or "civil defense shelter", download it as GeoJSON or Shapefile, read it with gpd.read_file() and print .crs.
- Run the .explore() method on the GeoDataFrame you read and check by eye whether the points land in the right place on the map. If no points appear, or they appear in odd places, suspect a coordinate system problem.
- In QGIS, load the same file with Layer > Add Layer > Add Vector Layer, then right-click the layer > Properties > Source tab and compare the CRS shown there with the value printed by .crs.
Common questions
Q. I installed GeoPandas but I get an import error. Why?
A. GeoPandas depends on C-based libraries such as GDAL, Fiona and Shapely, so installation with pip install alone can fail in some environments. Using a conda environment, or installing with conda install -c conda-forge geopandas from the conda-forge channel, often reduces dependency problems.
Q. To read a .shp file, do the .dbf and .prj files also need to be in the same folder?
A. Yes. A Shapefile is not a single file; several files such as .shp, .dbf, .prj and .shx together make one layer. These files must be in the same folder for gpd.read_file() to read both the attributes and the coordinate system information.
Q. The number of rows after the spatial join is larger than in the original. Is that an error?
A. It may not be. If one point overlaps several polygons, one row is created for each polygon, so the number of rows in the result increases. If duplicates are a problem for the analysis you intend, switch to how="left" or tidy up with .drop_duplicates(). First check which polygons created the duplicates with joined.index_right.value_counts().
What comes next
Once you are used to the flow of reading, converting coordinates and spatial joining in GeoPandas, you no longer have to process disaster data that keeps changing by hand each time. If you save the code, even when a new flood zone file arrives tomorrow, you can run the same analysis right away by changing only the path. At first you will often get stuck on a column name typo or a coordinate system mismatch, but the fastest fix each time is the habit of printing .columns and .crs to check. If you can now read and join files, the next step is to develop the result into spatial operations such as buffering and area calculation. A later post in this series covers how to calculate distance and area on a GeoDataFrame and automatically extract risk zones.
This is an English adaptation of a post in the Korean GeoAI basics series. The original is here, and more learning materials are on GeoAI for Disaster Safety.
This post was drafted with the help of AI tools and reviewed by the author. Tool features and data portals change over time, so check the official documentation when you practice.
Comments
Post a Comment