Skip to main content

Session 0 - 08/19/2026

The Geospatial Ecosystem

Colab link

Open In Colab
Code
# only run this if you are on Colab! 
# git clone https://github.com/ftl-brazil-2026/ebook.git
# pip install -r requirements.txt

Before diving into the breadth of geospatial ecosystems, let’s get to know our FTL Brasil community a little better.

Who are we? Where are we from?

Code
import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt 
import os 
Code
os.getcwd()
'/Users/macuser/Documents/UN/ebook/fundamentals_gis_rs/week0'
Code
# lets read our csv with the location of everyone
df = pd.read_excel('data/NOS-FTL-Brasil.xlsx')

df.head()
ID De onde você é? (Escreva como: Cidade/SG.  exemplo: Pindamonhangaba/SP . Tarauca/AC , catole do rocha/PB)\n\n
0 1 Fortaleza-CE
1 2 RECIFE/PE
2 3 Limeira/SP
3 4 Curitiba - Paraná
4 5 Viamão/RS

Data cleaning

Every data scientist’s favorite thing.

Free text varies a lot: different separators (/, -, ,), abbreviated vs. full state names, prefixes like “Sou de…” (“I’m from…”). So we only do a light cleanup before geocoding. We don’t try to split city/state by hand: cases like "Minas - Pouso Alegre" (reversed order!) would make that fragile. Instead, we send the whole string to Nominatim, which is already good at interpreting free text and in practice solves this for us.

Code
place= df.columns[1]
df.rename(columns={place:'lugar'},inplace=True)
Code
import re

def clean_place(raw: str) -> str:
    s = raw.strip()
    s = re.sub(r'(?i)^sou de\s+', '', s)   # strips prefixes like "Sou de Sobral/CE" ("I'm from...")
    s = re.sub(r'\s+', ' ', s)              # repeated spaces
    s = s.strip(' -,/')                     # stray separators at the ends
    return s

df['lugar_clean'] = df['lugar'].apply(clean_place)
df['lugar_clean'].unique()
<ArrowStringArray>
[            'Fortaleza-CE',                'RECIFE/PE',
               'Limeira/SP',        'Curitiba - Paraná',
                'Viamão/RS',                'Recife/PE',
                'Fortaleza',                 'Betim/MG',
   'São José dos Campos/SP',                'Toledo/PR',
            'Santarém/Pará',          'Santarém - Pará',
                  'Ijuí/RS',            'Fortaleza, ce',
               'Niterói/RJ',              'Gravataí/RS',
         'Florianópolis/SC',               'Pinhais/PR',
               'Goiânia/GO', 'Campos dos Goytacazes/RJ',
      'Rio de Janeiro / RJ',           'Porto velho/RO',
        'Campina Grande/PB',                 'Belém/PA',
              'Brasília/DF',      'Lauro de Freitas/BA',
          'Passa Quatro/MG',       'Glória do Goitá/PE',
               'Betim - MG',            'Araraquara/SP',
              'Floresta/PR',             'Rio Claro/SP',
   'Presidente Prudente/SP',           'Santa Maria/RS',
              'Salvador/BA',        'Rio de Janeiro/RJ',
           'João Pessoa/PB',            'Holambra - SP',
                 'Timbó/SC', 'Campos dos goytacazes/RJ',
            'São Luís / MA',             'São Paulo/SP',
 'São José do Rio Preto/SP',                'Penedo/AL',
               'Maringá/PR',                'Cuiabá/MT',
                'São Paulo',                'Sobral/CE',
 'São Bernardo do Campo/SP',                'Caxias/MA',
        'Três Corações, MG',     'Minas - Pouso Alegre',
           'Santo André/SP',               'Niterói RJ']
Length: 54, dtype: str

Geocoding

Now let’s turn each lugar (“place”: free text, exactly as each person filled it in on the form) into coordinates (latitude, longitude), using the public Nominatim API (OpenStreetMap).

Code
from pathlib import Path
from geopy.geocoders import Nominatim
from geopy.extra.rate_limiter import RateLimiter

CACHE_PATH = Path('data/geocoded_cache.csv')

if CACHE_PATH.exists():
    # cache everything, so we don't hit the Nominatim API again
    cache = pd.read_csv(CACHE_PATH)
else:
    # user_agent is required by Nominatim's usage policy
    geolocator = Nominatim(user_agent='ftl-brasil-tmj', 
                           timeout=10)
    # 1 request per second
    # swallow_exceptions keeps a single failure from breaking the loop
    geocode = RateLimiter(geolocator.geocode, 
                          min_delay_seconds=1, 
                          error_wait_seconds=5,
                           max_retries=2, 
                           swallow_exceptions=True)

    unique_places = df[['lugar_clean']].drop_duplicates().reset_index(drop=True)
    unique_places['location'] = unique_places['lugar_clean'].apply(lambda p: geocode(p, country_codes='br'))
    unique_places['lat'] = unique_places['location'].apply(lambda loc: loc.latitude if loc else None)
    unique_places['lon'] = unique_places['location'].apply(lambda loc: loc.longitude if loc else None)
    unique_places['matched_address'] = unique_places['location'].apply(lambda loc: loc.address if loc else None)

    cache = unique_places[['lugar_clean', 'lat', 'lon', 'matched_address']]
    cache.to_csv(CACHE_PATH, index=False)

# join it back into our original df
df = df.merge(cache, on='lugar_clean', how='left')

# here we check the rows that could not be geocoded
nao_geocodificados = df[df['lat'].isna()]
print(f"{len(nao_geocodificados)} of {len(df)} rows were not geocoded")
nao_geocodificados
0 de 57 linhas não foram geocodificadas
ID lugar lugar_clean lat lon matched_address
Code
df.head()
ID lugar lugar_clean lat lon matched_address
0 1 Fortaleza-CE Fortaleza-CE -3.793217 -38.528036 Fortaleza, Ceará, Região Nordeste, Brasil
1 2 RECIFE/PE RECIFE/PE -8.058493 -34.884819 Recife, Pernambuco, Região Nordeste, Brasil
2 3 Limeira/SP Limeira/SP -22.561507 -47.401766 Limeira, São Paulo, Região Sudeste, Brasil
3 4 Curitiba - Paraná Curitiba - Paraná -25.429596 -49.271272 Curitiba, Paraná, Região Sul, Brasil
4 5 Viamão/RS Viamão/RS -30.081934 -51.026193 Viamão, Rio Grande do Sul, Região Sul, Brasil
Code
# let's convert our data into a GeoDataFrame so we can work with it spatially

gdf = gpd.GeoDataFrame(
    df.dropna(subset=['lat', 'lon']),
    geometry=gpd.points_from_xy(df['lon'], df['lat']),
    crs='EPSG:4326',
)
gdf.head()
ID lugar lugar_clean lat lon matched_address geometry
0 1 Fortaleza-CE Fortaleza-CE -3.793217 -38.528036 Fortaleza, Ceará, Região Nordeste, Brasil POINT (-38.52804 -3.79322)
1 2 RECIFE/PE RECIFE/PE -8.058493 -34.884819 Recife, Pernambuco, Região Nordeste, Brasil POINT (-34.88482 -8.05849)
2 3 Limeira/SP Limeira/SP -22.561507 -47.401766 Limeira, São Paulo, Região Sudeste, Brasil POINT (-47.40177 -22.56151)
3 4 Curitiba - Paraná Curitiba - Paraná -25.429596 -49.271272 Curitiba, Paraná, Região Sul, Brasil POINT (-49.27127 -25.4296)
4 5 Viamão/RS Viamão/RS -30.081934 -51.026193 Viamão, Rio Grande do Sul, Região Sul, Brasil POINT (-51.02619 -30.08193)
Code
# let's take a quick look at the data 
gdf.plot()

improving the plot

We can do better than that, right? Come on.

  • How?

Let’s use the data available in our geospatial ecosystem.

Starting with the GEOBR library. See more on our Awesome-FTL page.

Code
# downloading the polygon of our land, Brazil
import geobr

Map of where the participants are from

Code
# Brazilian states, straight from IBGE via geobr
brasil_gdf = geobr.read_state(year=2020)
brasil_gdf.head()
code_state name_state abbrev_state code_region name_region year geometry
0 11.0 Rondônia RO 1.0 Norte 2020.0 POLYGON ((-65.3815 -10.42907, -65.37916 -10.41...
1 12.0 Acre AC 1.0 Norte 2020.0 POLYGON ((-71.07772 -9.82774, -71.08554 -9.839...
2 13.0 Amazonas AM 1.0 Norte 2020.0 POLYGON ((-69.89403 -4.00068, -69.7123 -3.0006...
3 14.0 Roraima RR 1.0 Norte 2020.0 POLYGON ((-63.95934 2.46763, -63.96041 2.47416...
4 15.0 Pará PA 1.0 Norte 2020.0 MULTIPOLYGON (((-51.42367 -0.43661, -51.42073 ...
Code
# brasil_gdf comes in SIRGAS2000 (EPSG:4674), our points in WGS84 (EPSG:4326)
# -- we reproject the points to the polygon's CRS before overlaying the two
gdf_plot = gdf.to_crs(brasil_gdf.crs)

fig, ax = plt.subplots(figsize=(7, 8))

brasil_gdf.plot(ax=ax, color='#f0f0f0', edgecolor='#898781', linewidth=0.6)
gdf_plot.plot(ax=ax, markersize=30, color='#e63946', alpha=0.85, edgecolor='white', linewidth=0.4)

ax.set_title('Where the Future Tech Leaders Brasil participants are from', fontsize=13, fontweight='bold')
ax.set_axis_off()
plt.show()

Can we do better? Certainly

Code
# downloading the municipality data
muni = geobr.read_municipality(year=2020)
muni.plot()

Code
## let's run a spatial query to get the municipalities

new_gdf = muni.sjoin(
    gdf.to_crs(muni.crs),
    how="inner",
    predicate="intersects"
)

# quick plot
new_gdf.plot()

Code
new_gdf.columns
Index(['code_muni', 'name_muni', 'code_state', 'abbrev_state', 'name_state',
       'code_region', 'name_region', 'year', 'geometry', 'index_right', 'ID',
       'lugar', 'lugar_clean', 'lat', 'lon', 'matched_address'],
      dtype='str')
Code
# add a new column with the number of participants per city
nn = new_gdf.groupby('name_muni').agg(
    num_part=('code_muni','count')
)[['num_part']]

# merge the information
new_gdf = new_gdf.merge(
    nn,
    how='inner',
    on='name_muni'
)

## now our gdf has the number of students per city
new_gdf.head(2)
code_muni name_muni code_state abbrev_state name_state code_region name_region year geometry index_right ID lugar lugar_clean lat lon matched_address num_part_x num_part_y
0 1100205.0 Porto Velho 11.0 RO Rondônia 1.0 Norte 2020.0 POLYGON ((-62.86662 -7.97587, -62.85336 -7.987... 22 23 Porto velho/RO porto velho/ro -8.749453 -63.873544 Porto Velho, Rondônia, Região Norte, Brasil 1 1
1 1501402.0 Belém 15.0 PA Pará 1.0 Norte 2020.0 POLYGON ((-48.35304 -1.22103, -48.36552 -1.229... 51 52 Belém/PA belém/pa -1.450560 -48.468245 Belém, Pará, Região Norte, Brasil 2 2

Location map with municipalities

Code
import matplotlib.pyplot as plt
import matplotlib as mpl

fig, ax = plt.subplots(figsize=(7, 8))

brasil_gdf.plot(
    ax=ax,
    color="#162551",
    edgecolor="#E6E2D7",
    linewidth=0.6
)

cmap = plt.cm.Wistia
norm = mpl.colors.Normalize(vmin=1, vmax=3)

new_gdf.plot(
    ax=ax,
    column='num_part',
    markersize=30,
    cmap=cmap,
    norm=norm,
    alpha=0.85,
    edgecolor='white',
    linewidth=0.4
)

# Legend/colorbar
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])

# cbar = fig.colorbar(sm, ax=ax, shrink=0.6, pad=0.02)
# cbar.set_ticks([1, 2, 3])
# cbar.set_label('Number of participants')

ax.set_title('FTL Brasil participants', fontsize=13, fontweight='bold')
ax.set_axis_off()

plt.show()

## Can this map be improved? Certainly

Show us one of your ideas!

Don’t know what a spatial query is yet?

  • Don’t wait: go check out our introductory Python + GIS classes
  • GitHub link: github-ftl-brasil

Interactive map

A static map is great for printing or putting on a slide, but to explore geospatial data day to day we almost always want something clickable: zoom in, see the name of each city, etc.

Here we use Folium, which is basically Python talking to Leaflet.js under the hood: you build the map in Python, and it generates a self-contained HTML/JS page that runs in the browser, with no server needed.

If you can’t see the map in your notebook, you need to trust it:

uv run jupyter trust fundamentals_gis_rs/week0/space_tech_ecossystem.ipynb
Code
import folium
from folium.plugins import MarkerCluster

# the IBGE polygon is very detailed (great for analysis, heavy for the web) -- we simplify it
# for display only, without changing the original brasil_gdf
brasil_simple = brasil_gdf.to_crs(4326)
brasil_simple['geometry'] = brasil_simple.geometry.simplify(0.02, preserve_topology=True)

m = folium.Map(location=[-14.2, -51.9], zoom_start=4, tiles='cartodbpositron')

folium.GeoJson(
    brasil_simple,
    name='States',
    style_function=lambda feature: {
        'fillColor': '#f0f0f0',
        'color': '#898781',
        'weight': 0.8,
        'fillOpacity': 0.3,
    },
).add_to(m) # add to the map 

#cluster = MarkerCluster(name='Participants').add_to(m)
for _, row in gdf.iterrows():
    folium.CircleMarker(
        location=[row['lat'], row['lon']],
        radius=6,
        color='#e63946',
        fill=True,
        fill_color='#e63946',
        fill_opacity=0.85,
        popup=folium.Popup(f"<b>{row['lugar_clean']}</b><br>{row['matched_address']}", max_width=250),
    ).add_to(m)

folium.LayerControl().add_to(m)
m
Make this Notebook Trusted to load map: File -> Trust Notebook

Testing some APIs

Which provider? ESA - Destination Earth - Service: Earth Data Hub. Earth Data Hub

This one is about expanding our repertoire of geospatial data. Could we start right away with the Google Earth Engine API? We could… but that’s what most people already do. Let’s be the artists of our time, as Chico Science used to sing.

So let’s test the CDSE (Copernicus Data Space Ecosystem) API key. Through it we can download lots of data (free of charge, but with a quota): worldwide elevation data (Digital Terrain Model, DTM), climate data, Sentinel-1 data, Sentinel-2 data, and so on.

Code
# import the module that loads environment variables into our kernel
from dotenv import load_dotenv
import os

# load the variables into our kernel 
load_dotenv()
True
Code
os.getenv("EXEMPLO_TOSCO")
'senha_papito_12345'
Code
## first, let's check that the service is working.
import xarray as xr
EARTH_HUB_API_KEY=os.getenv("EARTH_HUB_API_KEY")
test_dataset_url = xr.open_dataset(
    f"https://edh:{EARTH_HUB_API_KEY}@data.earthdatahub.destine.eu/private/test-dataset-v0.zarr",
    chunks={},
    engine="zarr",
)
test_dataset_url
<xarray.Dataset> Size: 4GB
Dimensions:               (latitude: 720, longitude: 1440,
                           age_band_lower_bound: 14, year: 71)
Coordinates:
  * latitude              (latitude) float64 6kB 90.0 89.75 ... -89.5 -89.75
  * longitude             (longitude) float64 12kB 0.0 0.25 0.5 ... 359.5 359.8
  * age_band_lower_bound  (age_band_lower_bound) int64 112B 0 5 10 ... 55 60 65
  * year                  (year) int64 568B 1950 1951 1952 ... 2018 2019 2020
Data variables:
    demographic_totals    (latitude, longitude, age_band_lower_bound, year) float32 4GB dask.array<chunksize=(180, 180, 14, 2), meta=np.ndarray>

Let’s download climate data from the ERA5 dataset.

Read more about ERA5

ERA5 is a climate dataset with data since 1940 for many parameters such as temperature, precipitation, wind components, surface pressure, dew point temperature, and so on. It is a kind of hourly record of the Earth’s climate. It takes the available observations and combines them with a physical model of the atmosphere to produce a consistent, continuous representation of the state of the atmosphere.

Very roughly, 0.25 degrees of the ERA5 grid corresponds to “25 km”, depending a lot on the latitude you are interested in.

Code
import xarray as xr

EARTH_HUB_API_KEY=os.getenv("EARTH_HUB_API_KEY")

ds = xr.open_dataset(
    f"https://edh:{EARTH_HUB_API_KEY}@data.earthdatahub.destine.eu/era5/reanalysis-era5-single-levels-v0.zarr",
    chunks={},
    engine="zarr",
)
ds
<xarray.Dataset> Size: 406TB
Dimensions:     (valid_time: 757512, latitude: 721, longitude: 1440)
Coordinates:
  * valid_time  (valid_time) datetime64[ns] 6MB 1940-01-01 ... 2026-05-31T23:...
  * latitude    (latitude) float64 6kB 90.0 89.75 89.5 ... -89.5 -89.75 -90.0
  * longitude   (longitude) float64 12kB 0.0 0.25 0.5 0.75 ... 359.2 359.5 359.8
    number      int64 8B ...
    surface     float64 8B ...
Data variables: (12/129)
    alnid       (valid_time, latitude, longitude) float32 3TB dask.array<chunksize=(4320, 64, 64), meta=np.ndarray>
    alnip       (valid_time, latitude, longitude) float32 3TB dask.array<chunksize=(4320, 64, 64), meta=np.ndarray>
    aluvd       (valid_time, latitude, longitude) float32 3TB dask.array<chunksize=(4320, 64, 64), meta=np.ndarray>
    aluvp       (valid_time, latitude, longitude) float32 3TB dask.array<chunksize=(4320, 64, 64), meta=np.ndarray>
    anor        (valid_time, latitude, longitude) float32 3TB dask.array<chunksize=(4320, 64, 64), meta=np.ndarray>
    asn         (valid_time, latitude, longitude) float32 3TB dask.array<chunksize=(4320, 64, 64), meta=np.ndarray>
    ...          ...
    viiwn       (valid_time, latitude, longitude) float32 3TB dask.array<chunksize=(4320, 64, 64), meta=np.ndarray>
    vilwd       (valid_time, latitude, longitude) float32 3TB dask.array<chunksize=(4320, 64, 64), meta=np.ndarray>
    vilwe       (valid_time, latitude, longitude) float32 3TB dask.array<chunksize=(4320, 64, 64), meta=np.ndarray>
    vilwn       (valid_time, latitude, longitude) float32 3TB dask.array<chunksize=(4320, 64, 64), meta=np.ndarray>
    z           (valid_time, latitude, longitude) float32 3TB dask.array<chunksize=(4320, 64, 64), meta=np.ndarray>
    zust        (valid_time, latitude, longitude) float32 3TB dask.array<chunksize=(4320, 64, 64), meta=np.ndarray>
Attributes:
    Conventions:             CF-1.7
    GRIB_centre:             ecmf
    GRIB_centreDescription:  European Centre for Medium-Range Weather Forecasts
    GRIB_edition:            1
    GRIB_subCentre:          0
    history:                 2025-12-04T16:25 GRIB to CDM+CF via cfgrib-0.9.1...
    institution:             European Centre for Medium-Range Weather Forecasts

Let’s take a peek at how easily we can access large climate datasets with our API.

To do that, I’ll plot the monthly precipitation for the last 5 years at a point in the state of Santa Catarina.

Want to plot it for an area you care about? Find the point you’re interested in, change the values, run it again, done :)


Important details:

Since we are working with a RASTER made of grid cells, xarray selects the grid cell nearest to the point, and these grid cells have a 0.25° resolution.

ERA5 comes at hourly resolution, so before plotting we aggregate (resample(...).sum()) the hours within each month to get the monthly total.

Code
# lat lon 
# Point in the municipality of Araranguá, Santa Catarina 

lat = -28.93966
lon = -49.37621

# a few other quirks 
# ERA5 uses the 0-360° longitude convention, not -180/180°.
# Without this conversion, .sel(method="nearest") snaps to some point off the coast of Africa.
lon_360 = lon % 360

# Selecting from the ERA5 data
rain = (
    ds["tp"]
    .sel(
        latitude=lat,
        longitude=lon_360,
        method="nearest",
    )
    .sel(
        valid_time=slice("2021-01-01", "2025-12-01")      ## slicing the last 5 years of climate data.
    )
)

## now we have a chunk with only the precipitation data, still hourly
rain
<xarray.DataArray 'tp' (valid_time: 43104)> Size: 172kB
dask.array<getitem, shape=(43104,), dtype=float32, chunksize=(4320,), chunktype=numpy.ndarray>
Coordinates:
  * valid_time  (valid_time) datetime64[ns] 345kB 2021-01-01 ... 2025-12-01T2...
    latitude    float64 8B -29.0
    longitude   float64 8B 310.5
    number      int64 8B ...
    surface     float64 8B ...
Attributes: (12/31)
    GRIB_NV:                                  0
    GRIB_Nx:                                  1440
    GRIB_Ny:                                  721
    GRIB_cfName:                              unknown
    GRIB_cfVarName:                           tp
    GRIB_dataType:                            fc
    ...                                       ...
    GRIB_typeOfLevel:                         surface
    GRIB_units:                               m
    GRIB_uvRelativeToGrid:                    0
    long_name:                                Total precipitation
    standard_name:                            unknown
    units:                                    m
Code
# "tp" is hourly accumulated precipitation; to get the monthly TOTAL, 
# we add up all the hours in each month 
rain_monthly = rain.resample(valid_time="1MS").sum()
rain_monthly
<xarray.DataArray 'tp' (valid_time: 60)> Size: 240B
dask.array<stack, shape=(60,), dtype=float32, chunksize=(1,), chunktype=numpy.ndarray>
Coordinates:
  * valid_time  (valid_time) datetime64[ns] 480B 2021-01-01 ... 2025-12-01
    latitude    float64 8B -29.0
    longitude   float64 8B 310.5
    number      int64 8B ...
    surface     float64 8B ...
Attributes: (12/31)
    GRIB_NV:                                  0
    GRIB_Nx:                                  1440
    GRIB_Ny:                                  721
    GRIB_cfName:                              unknown
    GRIB_cfVarName:                           tp
    GRIB_dataType:                            fc
    ...                                       ...
    GRIB_typeOfLevel:                         surface
    GRIB_units:                               m
    GRIB_uvRelativeToGrid:                    0
    long_name:                                Total precipitation
    standard_name:                            unknown
    units:                                    m
Code
rain_mm = rain_monthly * 1000  # meters -> millimeters

rain_mm
<xarray.DataArray 'tp' (valid_time: 60)> Size: 240B
dask.array<mul, shape=(60,), dtype=float32, chunksize=(1,), chunktype=numpy.ndarray>
Coordinates:
  * valid_time  (valid_time) datetime64[ns] 480B 2021-01-01 ... 2025-12-01
    latitude    float64 8B -29.0
    longitude   float64 8B 310.5
    number      int64 8B ...
    surface     float64 8B ...
Attributes: (12/31)
    GRIB_NV:                                  0
    GRIB_Nx:                                  1440
    GRIB_Ny:                                  721
    GRIB_cfName:                              unknown
    GRIB_cfVarName:                           tp
    GRIB_dataType:                            fc
    ...                                       ...
    GRIB_typeOfLevel:                         surface
    GRIB_units:                               m
    GRIB_uvRelativeToGrid:                    0
    long_name:                                Total precipitation
    standard_name:                            unknown
    units:                                    m
Code
import plotly.express as px
import plotly.io as pio
pio.renderers.default = "notebook"

fig = px.bar(
    rain_mm.to_dataframe(name="rainfall_mm").reset_index(),
    x="valid_time",
    y="rainfall_mm",
    title=(
        f"Monthly precipitation in Araranguá - Santa Catarina. ERA5 data <br>"
        f"Point: {lat:.2f}°, {lon:.2f}°"
    ),
    labels={
        "valid_time": "Month",
        "rainfall_mm": "Precipitation (mm/month)",
    },
)

fig.update_traces(
    marker_color="#457b9d",
    hovertemplate=(
        "<b>%{x|%B %Y}</b><br>"
        "Precipitation: %{y:.1f} mm"
        "<extra></extra>"
    ),
)

fig.update_layout(
    template="plotly_white",
    hovermode="x unified",
    height=500,
)

fig.update_xaxes(showgrid=True)
fig.update_yaxes(showgrid=True, rangemode="tozero")

fig.show()

Curious?