Python for GIS: Getting Started

Python for GIS: Getting Started

The first time I wrote a script to process a hundred shapefiles, I felt like I had been handed a superpower. The task was dull: reproject every file in a folder, clip it to a study area, and save the result as a GeoPackage. By hand it would have taken most of a Friday, with the usual mistakes of clicking the wrong layer or forgetting one file. The script was twenty lines long, took ten minutes to write, and ran in under two. I made a cup of coffee and watched it finish. I have never gone back to clicking through the same twelve steps twice.

If you work in GIS, Python is the most useful skill you can add to your toolbox. It is free, readable, supported by an enormous community, and it connects to nearly every GIS tool that exists. You don’t need to become a software engineer. You need to learn enough to automate the boring parts, do things your GIS can’t, and make your work repeatable. This guide takes you from zero to your first working geospatial scripts: what to install, the Python you actually need, the key libraries, a first analysis, and the habits that keep your projects tidy.

This is the entry point to the series. For the full map of the territory, read Geospatial Development & Automation: The Ultimate Guide.

Diagram: A few core libraries cover vector data, rasters, projections, reading files and mapping.
A few core libraries cover vector data, rasters, projections, reading files and mapping.

Why Python for GIS?

  • Automation: repeat tasks on hundreds of files without errors or boredom.
  • Scale: process datasets too large or too numerous to handle by clicking.
  • Reproducibility: a script documents exactly what you did, and can be rerun, shared and audited.
  • Integration: connect GIS with spreadsheets, databases, web services and machine learning.
  • Flexibility: do analyses that no menu offers.
  • Careers: Python is among the most requested skills in GIS job advertisements. See How to Become a GIS Analyst: Roadmap and Is GIS a Good Career? Complete Guide.

Python doesn’t replace desktop GIS. It complements it. I still open QGIS to look at data, style maps and explore. I use Python when a task repeats, grows large or needs to be exactly reproducible.


The Python Ecosystem for GIS at a Glance

Several libraries work together. It helps to know which one does what.

LibraryWhat it does
GDAL/OGRThe foundation: reads and writes hundreds of raster and vector formats. Most other tools use it.
ShapelyGeometry objects and operations: points, lines, polygons, buffers, intersections.
pyprojCoordinate reference systems and transformations.
GeoPandasVector data as tables with geometry. The best starting point for most vector work.
pyogrio and FionaFast reading and writing of vector files, used by GeoPandas.
RasterioReading, writing and processing raster data such as GeoTIFFs.
Xarray and rioxarrayMulti-dimensional rasters and time series, with labeled axes.
NumPyFast arrays of numbers, the basis of raster calculations.
pandasTables and data analysis.
MatplotlibStatic plots and maps.
Folium and similar toolsInteractive web maps from Python.
PySALSpatial statistics.
OSMnx and NetworkXStreet networks and routing.
PyQGIS and ArcPyPython interfaces to automate QGIS and ArcGIS Pro.

You don’t need all of them. For your first months, GeoPandas for vectors and Rasterio for rasters will cover most needs. See Best Free and Open-Source GIS Tools for the wider open-source landscape.


Step 1: Install Python the Right Way

Geospatial libraries depend on compiled components, such as GDAL and PROJ, which can be troublesome to install with plain tools. The most reliable approach for beginners is an environment manager that handles those dependencies.

Option A: conda or mamba (recommended)

Install a Miniforge distribution, which gives you conda and the faster mamba, and uses the community-maintained conda-forge channel, where the geospatial packages are well supported.

Then create a dedicated environment for your GIS work:

conda create -n gis -c conda-forge python=3.12 geopandas rasterio rioxarray matplotlib jupyterlab
conda activate gis

(Use mamba instead of conda if you prefer speed.) Package versions move on, so if a version is not available, let the tool choose the newest Python that all the packages support.

Option B: pip and a virtual environment

Modern releases of the main geospatial libraries are available as ready-made wheels, so pip often works:

python -m venv gis-env
source gis-env/bin/activate        # on Windows: gis-env\Scripts\activate
pip install geopandas rasterio rioxarray matplotlib jupyterlab

If you meet installation errors, switch to conda. Don’t fight it.

Why environments matter

An environment is an isolated set of libraries for one project. It prevents the classic nightmare of a script that worked last month and now fails because an update changed something. One environment per project (or per family of projects) is a golden rule. Export your environment to a file so that you, or a colleague, can recreate it.

Python inside QGIS and ArcGIS Pro

  • QGIS includes its own Python and a Python Console (Plugins > Python Console), already loaded with the QGIS libraries (PyQGIS).
  • ArcGIS Pro includes its own Python environment with ArcPy, and notebooks inside the application.

These are separate from the environment you just created. They are excellent for automating those applications, and we will meet them later. For general geospatial work, use your own environment.


Step 2: Choose Where to Write Code

  • JupyterLab (notebooks): an interactive environment where you write and run code in small cells, and see maps and plots right under them. Perfect for exploring, learning and documenting. Start it with jupyter lab in your terminal.
  • VS Code or PyCharm: full editors for longer scripts and projects, with debugging, search and Git support.
  • A plain text editor and the terminal: it works for small scripts.

I suggest: notebooks for exploration, scripts for things you will run repeatedly. Many professionals use both, moving code from the notebook into a script once it works.


Step 3: The Python You Actually Need

You don’t need to master the whole language. Here is the subset that covers most GIS scripting. Try each snippet in a notebook.

Variables and basic types

name = "Riverside"          # text (string)
population = 25400          # integer
area_km2 = 12.75            # decimal number (float)
is_coastal = False          # boolean (True or False)

print(f"{name} has {population} people over {area_km2} km2")
print("Density:", round(population / area_km2, 1))

The f"..." form, an f-string, inserts values into text. You will use it constantly.

Lists and dictionaries

bands = ["red", "green", "blue", "nir"]      # a list: ordered items
bands.append("swir")
print(bands[0], len(bands))

layer = {"name": "roads", "crs": "EPSG:4326", "features": 1520}   # a dictionary: key and value pairs
print(layer["crs"])

Loops and conditions

for band in bands:
    print("Processing band:", band)

for n in [5, 50, 500]:
    if n > 100:
        print(n, "is large")
    elif n > 10:
        print(n, "is medium")
    else:
        print(n, "is small")

Python uses indentation (spaces) to mark blocks of code. Consistent indentation is not optional.

Functions

def area_in_hectares(area_m2):
    """Convert an area in square meters to hectares."""
    return area_m2 / 10000

print(area_in_hectares(250000))

Functions let you reuse a piece of logic, and give it a name. When you copy and paste the same lines twice, it is time for a function.

List comprehensions

areas = [120.5, 80.0, 310.2]
hectares = [a / 10000 for a in areas]

A compact way to build a list from another. Handy, though loops are fine while you learn.

Files and paths with pathlib

from pathlib import Path

data_dir = Path("data/raw")
for file in data_dir.glob("*.gpkg"):          # all GeoPackages in the folder
    print(file.name, file.stat().st_size)

out_file = Path("data/processed") / "result.gpkg"   # build paths with /

Use pathlib instead of manually joining strings. It works across Windows, macOS and Linux.

Handling errors

try:
    value = int("12a")
except ValueError:
    print("That is not a number, skipping")

In batch scripts, try and except stop one bad file from killing the whole run.

Reading the error messages

Python errors look scary, but they are helpful. Read the last line first: it names the error and says what happened. The lines above it show where. Most errors fall into a few kinds: a typo in a name (NameError), a wrong type (TypeError), a missing file (FileNotFoundError), or a missing key or column (KeyError). Copy the last line into a search engine, and you will find the answer.


Step 4: Your First Geospatial Script

Let’s do something real. We will read a polygon layer, check and change its coordinate system, calculate areas, make a map and save the result. Assume a file called districts.gpkg in a data folder.

import geopandas as gpd

# 1. Read the data
districts = gpd.read_file("data/districts.gpkg")

# 2. Look at it
print(districts.head())          # first rows of the attribute table
print(districts.crs)             # the coordinate reference system
print(len(districts), "features")

# 3. Reproject to a projected CRS in meters (replace with one suited to your area)
districts_m = districts.to_crs(epsg=32631)

# 4. Calculate area in square kilometers
districts_m["area_km2"] = districts_m.geometry.area / 1_000_000

# 5. Make a quick map
ax = districts_m.plot(column="area_km2", cmap="viridis", legend=True, figsize=(8, 8))
ax.set_axis_off()

# 6. Save the result
districts_m.to_file("data/districts_area.gpkg", driver="GPKG")

What each step teaches you:

If you can run this, you have just done in a few lines what would take a dozen clicks in a desktop GIS, and you can run it again tomorrow on a different file.


Step 5: Points From a Spreadsheet

One of the most common tasks: turning a table with coordinate columns into a spatial layer.

import pandas as pd
import geopandas as gpd

df = pd.read_csv("data/stations.csv")        # columns: name, lat, lon, ph

stations = gpd.GeoDataFrame(
    df,
    geometry=gpd.points_from_xy(df["lon"], df["lat"]),   # x is longitude, y is latitude
    crs="EPSG:4326"                                      # the CRS of the coordinates
)

stations.to_file("data/stations.gpkg", driver="GPKG")

Two details deserve attention. In points_from_xy, longitude (x) comes first. And you must state the CRS the coordinates are in (here WGS 84), because the table can’t tell you. Getting these wrong is the classic reason that points appear in the middle of the ocean.


Step 6: Coordinate Transformations With pyproj

When you need to convert a single coordinate or build your own logic, use pyproj:

from pyproj import Transformer

# always_xy=True means (longitude, latitude) order for geographic coordinates
transformer = Transformer.from_crs("EPSG:4326", "EPSG:32631", always_xy=True)

x, y = transformer.transform(2.3522, 48.8566)
print(round(x), round(y))

The always_xy=True option avoids axis order confusion, a notorious trap that we also see in web services. See Intro to Web GIS APIs and OGC Standards (WMS, WFS, WMTS).


Step 7: Automating a Batch Task

Now the payoff. Convert every Shapefile in a folder to GeoPackage, reprojected to a common CRS, with a log of what happened:

from pathlib import Path
import geopandas as gpd

in_dir = Path("data/raw")
out_dir = Path("data/processed")
out_dir.mkdir(parents=True, exist_ok=True)

target_crs = "EPSG:32631"      # replace with a CRS suited to your area

for shp in sorted(in_dir.glob("*.shp")):
    try:
        gdf = gpd.read_file(shp)
        if gdf.crs is None:
            print(f"SKIPPED {shp.name}: no CRS defined")
            continue
        gdf = gdf.to_crs(target_crs)
        gdf.to_file(out_dir / f"{shp.stem}.gpkg", driver="GPKG")
        print(f"OK      {shp.name}: {len(gdf)} features")
    except Exception as error:
        print(f"FAILED  {shp.name}: {error}")

Notice the habits: a loop over files, a check for a missing CRS, try and except so that one bad file does not stop the others, and a printed log. Those four elements turn a script into a dependable tool. Never assign a CRS to data you are unsure about. Stop and investigate, as explained in Top 10 Most Common GIS Errors and How to Fix Them.


Python Inside Your GIS: A First Taste

PyQGIS

Open the Python Console in QGIS and try:

layer = iface.activeLayer()
print(layer.name(), layer.featureCount())

iface is a ready-made object that represents the QGIS interface. You can also run any Processing tool from code. See Automating Workflows with ModelBuilder and QGIS Processing.

ArcPy

In ArcGIS Pro’s Python window:

import arcpy
arcpy.analysis.Buffer("roads", "roads_buffer_100m", "100 Meters")

This runs the same Buffer tool as the menu, with the same parameters. Scripting ArcPy and PyQGIS is a gentle way into Python if you already work in those applications.


Organizing a Project

Good habits at the start save you hours later.

A simple folder structure

my_project/
    data/
        raw/          original data, never edited
        processed/    outputs of your scripts
    notebooks/        exploration
    scripts/          reusable scripts
    outputs/          maps, tables, figures
    README.md         what the project is and how to run it
    environment.yml   the list of libraries

Principles

  • Never edit raw data. Scripts read from raw and write to processed.
  • Use relative paths (like data/raw) rather than paths specific to your computer, so the project works anywhere.
  • Name things clearly. Lowercase names with underscores, no spaces.
  • Write comments that explain why, not just what.
  • Keep a README with the project’s purpose, data sources and how to run the code.
  • Record your environment, for example with conda env export or a list of packages.
  • Use Git for version control, to track changes and recover from mistakes. Learn the basics early. It’s a habit that pays off for a lifetime.
  • Document data and results, in the spirit of Metadata in GIS: Why It Matters and How to Create It.

Debugging: How to Get Unstuck

Every programmer spends a large share of their time fixing errors. Some practical habits:

  1. Read the error message, starting with the last line.
  2. Print and inspect. Use print(), type(), .head(), .crs, .shape and .dtypes to see what you really have.
  3. Run one step at a time in a notebook, rather than a thirty-line block.
  4. Shrink the problem. Test on a tiny dataset.
  5. Check the usual suspects in GIS: a missing or mismatched CRS, invalid geometries (gdf.is_valid.all()), empty results after a spatial filter, wrong column names, mixed geometry types.
  6. Search the exact error message. Someone has met it before.
  7. Ask well. In a forum, provide the error, a minimal example and your versions.
  8. Take a break. Half of my hardest bugs dissolved after a walk.

Common Beginner Mistakes

  • Working outside an environment, then breaking everything with an update.
  • Calculating areas and distances in degrees. Reproject first.
  • Assigning a CRS instead of reprojecting. set_crs labels, to_crs converts. They are not the same.
  • Swapping longitude and latitude.
  • Editing raw data in place.
  • Hardcoding absolute paths such as C:\Users\me\Desktop\..., which break on any other computer.
  • Copying code without understanding it, and having no idea what to do when it fails.
  • Looping over rows when a vectorized operation exists. GeoPandas and NumPy operate on whole columns at once, and are much faster.
  • Ignoring warnings. They often point at real problems.
  • Trying to learn everything at once. Pick one library and one small project.
  • Not testing on a small sample before running on the full dataset.

A Learning Path That Works

  1. Install an environment and run the examples above.
  2. Learn basic Python: variables, loops, functions, files. A few weeks of regular practice.
  3. Automate one real, boring task from your own work. Motivation beats tutorials.
  4. Learn GeoPandas and Shapely in depth. See GeoPandas and Shapely: Vector Data in Python.
  5. Learn Rasterio and Xarray for imagery and grids. See Raster Processing in Python: Rasterio, Xarray, and NDVI from Code.
  6. Add SQL. See Spatial SQL Cheat Sheet.
  7. Use Git and share your work in a public portfolio.
  8. Explore web services and APIs. See Intro to Web GIS APIs and OGC Standards (WMS, WFS, WMTS).
  9. Automate your GIS software with PyQGIS or ArcPy, and visual tools. See Automating Workflows with ModelBuilder and QGIS Processing.
  10. Specialize: statistics, machine learning, web development or cloud processing.

Practice projects


AI Assistants and Learning Python

AI coding assistants can help you write and explain code, especially when you are stuck. Use them as a patient tutor and a fast first-draft writer, not as an oracle. Always read the code, test it on a small sample, and check the geospatial logic yourself: the CRS, the units and the geometry types. A model can confidently produce code that runs and gives wrong answers. Your spatial judgment is what makes the result trustworthy. See AI and Machine Learning in GIS.


Final Thoughts

Python can feel like a mountain from the bottom, and it is, in fact, a gentle slope. Every professional I know began with a single small script that did one boring thing. Your goal is not to become a programmer. It is to own your workflow: to turn the tasks you repeat into code you trust.

Install your environment today, run the first script on a layer of your own, and then pick one chore from your week that you will never do by hand again. That is the beginning.

Where to go next: go deeper into vector data with GeoPandas and Shapely: Vector Data in Python, then into grids and imagery with Raster Processing in Python: Rasterio, Xarray, and NDVI from Code.

Rachid Khouri

Rachid Khouri

Rachid Khouri is a CAD, BIM and GIS professional, Autodesk Authorized Developer, trainer and technical author with more than 30 years of experience, working with AutoCAD since 1992. He founded GISauthority.com to share practical guidance on GIS and spatial technologies.