In [1]:
import pandas as pd
from simpledbf import Dbf5
import geopandas as gpd
import requests
import zipfile
import io
import os
%matplotlib inline
In [2]:
PROVINCIAS_URL = "http://www.ign.gob.ar/descargas/geodatos/SHAPES/ign_provincia.zip"
DEPARTAMENTOS_URL = "http://www.ign.gob.ar/descargas/geodatos/SHAPES/ign_departamento.zip"
MUNICIPIOS_URL = "http://www.ign.gob.ar/descargas/geodatos/SHAPES/ign_municipio.zip"
PROVINCIAS_OUTPUT = "provincias"
DEPARTAMENTOS_OUTPUT = "departamentos"
MUNICIPIOS_OUTPUT = "municipios"
In [3]:
def download_and_unzip(url):
print('Downloading shapefile...')
r = requests.get(url)
z = zipfile.ZipFile(io.BytesIO(r.content))
print("Done")
z.extractall(path=".") # extract to folder
filenames = [y for y in sorted(z.namelist()) for ending in ['dbf', 'prj', 'shp', 'shx'] if y.endswith(ending)]
print(filenames)
In [5]:
download_and_unzip(PROVINCIAS_URL)
In [6]:
provincias = gpd.read_file("Provincia")
provincias.head()
Out[6]:
In [8]:
provincias.to_file(os.path.join(PROVINCIAS_OUTPUT, PROVINCIAS_OUTPUT) + ".shp")
In [4]:
download_and_unzip(DEPARTAMENTOS_URL)
In [107]:
departamentos = gpd.read_file("Departamento")
departamentos.head()
Out[107]:
In [108]:
# se corrige el id de departamentos, sacando el dígito inicial
departamentos["IN1"] = departamentos["IN1"].str[1:]
In [109]:
departamentos.to_file(os.path.join(DEPARTAMENTOS_OUTPUT, DEPARTAMENTOS_OUTPUT) + ".shp")
In [110]:
download_and_unzip(MUNICIPIOS_URL)
In [111]:
municipios = gpd.read_file("Municipio")
municipios.head()
Out[111]:
Los polígonos de algunos municipios están separados. Se juntan para solucionar la duplicidad de municipios.
In [112]:
print("Existen {} municipios con id duplicado, tienen geometrías POLYGON separadas".format(
len(municipios) - len(municipios.drop_duplicates("IN1"))
))
len(municipios), len(municipios.drop_duplicates("IN1"))
Out[112]:
Ejemplo: municipio de San Pedro de Jujuy tiene su geometría dividida en 2 polígonos.
In [113]:
municipios[municipios["IN1"] == "380224"]
Out[113]:
In [114]:
municipios[municipios["IN1"] == "380224"].plot()
Out[114]:
Se aplica el método "dissolve" para unir los polígonos de los municipios, generando una sola fila por id sin afectar la forma de los polígonos.
In [115]:
municipios_dissolved = municipios.dissolve(by='IN1').reset_index()
In [116]:
municipios_dissolved[municipios_dissolved["IN1"] == "380224"]
Out[116]:
In [117]:
municipios_dissolved[municipios_dissolved["IN1"] == "380224"].plot()
Out[117]:
In [118]:
municipios_dissolved.to_file(os.path.join(MUNICIPIOS_OUTPUT, MUNICIPIOS_OUTPUT) + ".shp")
In [ ]: