Skip to content

popmex – Examples

This page provides practical examples of using popmex for rates, maps and population projections.

Basic Examples

Example 1: Incidence rate by municipality

import pandas as pd
import popmex

pop = popmex.load("pop2020", cve_edo="31")
casos = pd.DataFrame({"CVEGEO": ["31050", "31101"], "casos": [420, 35]})   # your cases

df = pop[["CVEGEO", "pobtot"]].merge(casos, on="CVEGEO", how="left").fillna({"casos": 0})
df["tasa"] = popmex.rate(df["casos"], df["pobtot"])       # per 100,000
df.sort_values("tasa", ascending=False).head()

Example 2: Population of the year with the CONAPO projections

con = popmex.load("conapop", cve_edo="31")
pob_2025 = (con[con["ano"] == 2025]
            .groupby("cvegeo", as_index=False)["pob_total"].sum())

Example 3: Population pyramid of a state

import matplotlib.pyplot as plt

con = popmex.load("conapop", cve_edo="31")
y = con[con["ano"] == 2025]
ages = [c for c in con.columns if c.startswith("pob_") and c != "pob_total"]
men = y[y["sexo"].str.upper().str.startswith("HOM")][ages].sum()
women = y[y["sexo"].str.upper().str.startswith("MUJ")][ages].sum()

fig, ax = plt.subplots(figsize=(6, 5))
ax.barh(ages, -men, color="#1E6EC8", label="Men")
ax.barh(ages, women, color="#F08028", label="Women")
ax.legend(); plt.show()

Advanced Examples

Example 4: Map of the population of a city in hexagons

merida = popmex.extract_pop(year=2023, cve_edo="31",
                            locality=["Merida", "Uman", "Kanasin"])
merida.explore(column="population", cmap="inferno_r", tiles="CartoDB positron")

Example 5: Change between years in the same hexagons

gdl22 = popmex.extract_pop(2022, "14", "Guadalajara")[["h3", "population"]]
gdl23 = popmex.extract_pop(2023, "14", "Guadalajara")[["h3", "population"]]
cambio = gdl22.merge(gdl23, on="h3", suffixes=("_2022", "_2023"))
cambio["diff"] = cambio["population_2023"] - cambio["population_2022"]

Example 6: LandScan population by municipality

import rgeomex

mun = rgeomex.load("AGEM_inegi19_mx", cve_edo="31")
ls2020 = popmex.landscan_population(mun, year=2020, id_col="CVEGEO")
ls2020["population"].sum()          # 2,368,289 (Yucatán, LandScan 2020)

Example 7: The LandScan raster

import rasterio

with rasterio.open(popmex.get_landscan()) as r:
    print(r.count, r.descriptions[:3], r.res, r.crs)
    pop2024 = r.read(r.descriptions.index("pop_2024") + 1, masked=True)