### Installation Source: https://github.com/andreslomeliv/datosmex/blob/master/BANXICOpy/README.ipynb Install the BanxicoPy library using pip. ```bash pip install BanxicoPy ``` -------------------------------- ### BANXICOpy Usage Example Source: https://github.com/andreslomeliv/datosmex/blob/master/README.md Example of how to use the Banxico class from the BANXICOpy library to fetch economic series. ```python from BANXICOpy import Banxico # Se requiere un token proporcionado por el INEGI token = 'foobar' indicador = Banxico(token) indicador.obtener_df(indicadores = ['SF46405','SF46410'], nombres = ['USD','EURO'], inicio = '2020-01-01', fin = '2021-09-14') ``` -------------------------------- ### Route Calculation Examples Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Demonstrates equivalent ways to call the CalculateRoute function and display the result. ```python #ruteo.CalcularRuta(linea_inicial = linea_inicial, destino_final = destino_final, tipo_vehiculo = 1, ruta = 'optima') #ruteo.CalcularRuta(destino_inicial = destino_inicial, linea_final = linea_final, tipo_vehiculo = 1, ruta = 'optima') #ruteo.CalcularRuta(destino_inicial = destino_inicial, destino_final = destino_final, tipo_vehiculo = 1, ruta = 'optima') display(ruta_optima) ``` -------------------------------- ### Detailed Route Information Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Example of how to get detailed route information. ```python detalle_ruta = ruteo.DetalleRuta(linea_inicial = linea_inicial, linea_final = linea_final, tipo_vehiculo = 1, ruta = 'optima') display(detalle_ruta) ``` -------------------------------- ### INEGIpy Usage Example Source: https://github.com/andreslomeliv/datosmex/blob/master/README.md Example of how to use the Indicadores class from the INEGIpy library to fetch economic indicators. ```python from INEGIpy import Indicadores # Se requiere un token proporcionado por el INEGI token = 'foobar' indicador = Indicadores(token) indicador.obtener_df(indicadores = '628229', bancos = 'BIE', nombres = 'Inflación General', inicio = '2018-06', fin = '2021-12') ``` -------------------------------- ### Example Usage of LocalidadesAmanzanadas Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Demonstrates how to use the LocalidadesAmanzanadas function with concatenated keys and displays the tail of the resulting DataFrame. ```python localidades = marco.LocalidadesAmanzanadas(claves_concatenadas = ['01','09002','190310357'], as_geodf = False) display(localidades.tail()) ``` -------------------------------- ### BuscarLinea Example Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Example of using the BuscarLinea function from the routing module to find a line based on latitude and longitude. ```python linea_i = ruteo.BuscarLinea(lat, lng) display(linea_i) ``` -------------------------------- ### BuscarEntidad Example Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Example of using BuscarEntidad to search for 'papeleria' in entity '09' with a final registration of 5, without returning a GeoDataFrame. ```python df = denue.BuscarEntidad('papeleria', entidad='09', registro_final = 5, as_geodf=False) display(df) ``` -------------------------------- ### Fetching Localities Data Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Example of how to fetch locality data for specific municipalities within an entity and display it. ```python localidades = marco.LocalidadesAmanzanadas(entidades = '09', municipios = ['002','003','004','005'], as_geodf = False) display(localidades) ``` -------------------------------- ### Calculate the optimal route Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Example of using the CalcularRuta function to find an optimal route between two points. ```python ruta_optima = ruteo.CalcularRuta(linea_inicial = linea_inicial, linea_final = linea_final, tipo_vehiculo = 1, ruta = 'optima') ``` -------------------------------- ### Cuantificar() Function Call Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Example of how to call the Cuantificar() function with default parameters. ```python DENUE.Cuantificar(clave_area = '0', clave_actividad = '0', estrato = '0') ``` -------------------------------- ### Quantify data by activity class and stratum Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Example of using the Cuantificar function to count businesses by activity code and stratum. ```python df = denue.Cuantificar(clave_area = '09003', clave_actividad = ['464111', '464112'], estrato= '1') #farmacias con y sin minisuper en Coyoacán display(df) ``` -------------------------------- ### Localidades by Entidades and Municipios Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Example of how to retrieve locality data by specifying entity and municipality codes. This method limits the combinations of areas that can be queried. ```python # definir las claves en su forma concatenada en vez de separadas por nivel de agregación permite realizar dioferentes combinaciones entre áreas: # si se definen de manera separada una vez que se da una lista de áreas ya no se pueden definir los niveles siguiente. Es decir, si se pasa una lista de estados # no se puede definir un municipio, de manera que las posibilidades se reducen a una lista de estados, un estado con una lista de municipios, # un estado y un municipio con una lsita de localidades, y así sucesivamente. localidades = marco.LocalidadesAmanzanadas(entidades = '09', municipios = ['002','003','004','005'], as_geodf = False) display(localidades) ``` ``` Result: cvegeo cve_agee cve_agem cve_loc nom_loc \ 0 090020001 09 002 0001 Azcapotzalco 1 090030001 09 003 0001 Coyoacán 2 090040063 09 004 0063 Santa Rosa 3 090040010 09 004 0010 Cruz Blanca 4 090040050 09 004 0050 La Venta 5 090040073 09 004 0073 Los Aguacates 6 090040054 09 004 0054 Puerto las Cruces (Monte las Cruces) 7 090040020 09 004 0020 San Lorenzo Acopilco 8 090040001 09 004 0001 Cuajimalpa de Morelos 9 090050001 09 005 0001 Gustavo A. Madero ambito latitud longitud altitud pob viv cve_carta \ 0 URBANO 19.4841028 -99.1843606 2244 432205 134204 E14A39 1 URBANO 19.3502139 -99.1621456 2247 614447 191646 E14A39 2 RURAL 19.3233383 -99.2949614 2857 818 204 E14A39 3 RURAL 19.3177850 -99.3240103 2982 728 192 E14A39 4 RURAL 19.3343756 -99.3102128 2862 486 124 E14A39 5 RURAL 19.3699019 -99.3107319 2725 514 129 E14A39 6 RURAL 19.2948611 -99.3476211 3200 1233 323 E14A38 7 URBANO 19.3310047 -99.3256817 2936 26042 6627 E14A39 8 URBANO 19.3573503 -99.2997922 2780 186693 52530 E14A39 9 URBANO 19.4829453 -99.1134708 2230 1173351 340301 E14A39 estatus periodo 0 1 2015-06-01 1 1 2015-06-01 2 1 2015-06-01 3 1 2015-06-01 4 1 2015-06-01 5 1 2017-02-28 6 1 2015-06-01 7 1 2015-06-01 8 1 2015-06-01 9 1 2015-06-01 ``` ``` -------------------------------- ### Querying Multiple Series by List Source: https://github.com/andreslomeliv/datosmex/blob/master/BANXICOpy/README.ipynb Fetch data for multiple time series using a list of indicators and their names, with an optional start date. ```python # varias series dentro de una lista indicadores = ["SF61745", "SP68257", "SF43718"] nombres = ["Tasa Objetivo", "UDIS", "Tipo de Cambio"] df = bmx.obtener_series(indicadores, nombres, inicio = '2017-05-13') df.head() ``` -------------------------------- ### Search for a destination by name Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Example of using the BuscarDestino function to find a location by its name. ```python from INEGIpy import Ruteo token = "TuToken" ruteo = Ruteo(token) destino_inicial = ruteo.BuscarDestino(busqueda = 'palacio de bellas artes, ciudad de m', cantidad = 1) destino_final = ruteo.BuscarDestino(busqueda = ' zócalo, ciudad de m', cantidad = 1) display(destino_inicial) display(destino_final) ``` -------------------------------- ### Get Entities and Plot Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Retrieves entity data for specified names and plots the result. ```python edos = marco.Entidades(nombres = ['ciudad de méxico','méxico','querétaro','san luis','nuevo león']) edos.plot() ``` -------------------------------- ### Localidades by Concatenated Keys Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Example of how to retrieve locality data using concatenated keys, which allows for more flexible combinations of areas across different aggregation levels. ```python # en cambio, las claves concatenadas permiten diferentes municipios de diferentes entidades o incluso hacer combinaciones entre los niveles de agregación localidades = marco.LocalidadesAmanzanadas(claves_concatenadas = ['01','09002','190310357'], as_geodf = False) display(localidades.tail()) ``` ``` Result: cvegeo cve_agee cve_agem cve_loc nom_loc ambito latitud \ 392 010050106 01 005 0106 La Tomatina RURAL 21.9014614 393 010050007 01 005 0007 Los Arquitos RURAL 21.9234458 394 010050019 01 005 0019 Cieneguitas RURAL 21.8954869 395 090020001 09 002 0001 Azcapotzalco URBANO 19.4841028 396 190310357 19 031 0357 Anzures URBANO 25.6905483 longitud altitud pob viv cve_carta estatus periodo 392 -102.4151539 1962 1076 249 F13D18 1 2015-06-01 393 -102.3857450 1908 1214 252 F13D18 1 2015-06-01 394 -102.4265219 1990 208 54 F13D18 1 2015-06-01 395 -99.1843606 2244 432205 134204 E14A39 1 2015-06-01 396 -100.1183050 0397 5222 1521 G14C26 1 2015-06-01 ``` ``` -------------------------------- ### Find the nearest routing line by coordinates Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Example of using the BuscarLinea function to find the closest routing line to given coordinates. ```python linea_inicial = ruteo.BuscarLinea(lat = 19.435237353, lng = -99.141374223) # equvalente a buscar bellas artes pero con las coordenadas linea_final = ruteo.BuscarLinea(lat = 19.4326290000001, lng = -99.133203) # equivalente a buscar zócalo con las coordenadas display(linea_inicial) display(linea_final) ``` -------------------------------- ### Fetch and display street data for Monterrey Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb This snippet shows how to use the `marco.Vialidades` function to get street data for a specific municipality (Monterrey, '039') within an entity ('19') and then displays the first few rows of the resulting DataFrame. ```python mty_vialidades = marco.Vialidades(entidades='19',municipios='039') display(mty_vialidades.head()) ``` -------------------------------- ### Fetching Latest Opportunistic Data Source: https://github.com/andreslomeliv/datosmex/blob/master/BANXICOpy/README.ipynb Get the latest available data for a specific indicator, with options for increment type. ```python bmx.dato_oportuno("SF61745", 'tasa_objetivo', incremento='PorcAcumAnual') ``` -------------------------------- ### Fetch GDP data by state Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Fetch real GDP indicators for each state for the years 2019 and 2020. This involves defining the indicator IDs, getting the list of states, and then calling the `obtener_df` method. ```python indicadores = [str(i) for i in range(472080,472112)] # indicadores del PIB real por entidad federativa entidades = marco.Entidades() nombres = entidades.nom_agee.tolist() # nombres de las entidades pib_edos = inegi.obtener_df(indicadores = indicadores, nombres = nombres, inicio = '2019') display(pib_edos) ``` -------------------------------- ### Import and Initialization Source: https://github.com/andreslomeliv/datosmex/blob/master/BANXICOpy/README.ipynb Import the Banxico class and initialize it with your token. ```python # uso actual from BANXICOpy import Banxico ``` ```python token = '274066f5ed9caabbbbe6417dae8d4359f06ac5c853619436d9c82d55ed58fe83' bmx = Banxico(token) ``` -------------------------------- ### Initialize Banxico with token Source: https://github.com/andreslomeliv/datosmex/blob/master/BANXICOpy/README.md Initializing the Banxico object with an API token. ```python token = '274066f5ed9caabbbbe6417dae8d4359f06ac5c853619436d9c82d55ed58fe83' bmx = Banxico(token) ``` -------------------------------- ### Initialize clients Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Initialize the Indicadores client with an API token and the MarcoGeoestadistico client. ```python token = 'TuToken' inegi = Indicadores(token) marco = MarcoGeoestadistico() ``` -------------------------------- ### Initialize INEGIpy clients Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Initializes the DENUE, MarcoGeoestadistico, and Ruteo clients with API tokens. ```python token = 'TuToken' denue = DENUE(token) marco = MarcoGeoestadistico() token_ruteo = 'TuOtroToken' ruteo = Ruteo(token_ruteo) ``` -------------------------------- ### BuscarAreaAct Example Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Example of using BuscarAreaAct to search for 'soriana' within a specific area code '09003' and activity code '46', without returning a GeoDataFrame. ```python df = denue.BuscarAreaAct('soriana', clave_area = '09003', clave_actividad = '46', as_geodf = False) display(df) ``` -------------------------------- ### Fetching Base Monetaria with Annual Percentage Growth Source: https://github.com/andreslomeliv/datosmex/blob/master/BANXICOpy/README.md This snippet demonstrates how to fetch the 'Base Monetaria' series with an annual percentage growth increment and display the first few rows. ```python base = bmx.obtener_series('SF44043', 'Base Monetaria', inicio = '2020', incremento='PorcAnual') base.head() ``` -------------------------------- ### Instalación Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Instalación de la librería INEGIpy usando pip. ```bash pip install INEGIpy ``` -------------------------------- ### Import and Initialize Ruteo Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md This snippet shows how to import the Ruteo class and initialize it with an API token. ```python from INEGIpy import Ruteo token = 'TuToken' ruteo = Ruteo(token) ``` -------------------------------- ### Initialize Indicators object Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md This snippet shows how to import the Indicators class and initialize an object with an API token. ```python from INEGIpy import Indicadores token = 'TuToken' inegi = Indicadores(token) ``` -------------------------------- ### Import BANXICOpy Source: https://github.com/andreslomeliv/datosmex/blob/master/BANXICOpy/README.md Importing the Banxico class from the BANXICOpy library. ```python from BANXICOpy import Banxico ``` -------------------------------- ### Search for businesses by name and location, then plot results Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb This snippet demonstrates how to search for businesses (e.g., 'papeleria') within a specified radius around a given latitude and longitude using the DENUE client, and then plots the results. ```python df = denue.Buscar('papeleria', latitud = 19.32593, longitud = -99.17253, distancia = 3_000) df.plot() ``` -------------------------------- ### Get Indicator Catalog Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Retrieves a catalog of indicators, filtering by 'BIE', and displays the head of the resulting DataFrame. ```python indicadores = inegi.catalogo_indicadores('BIE') display(indicadores.head()) ``` -------------------------------- ### Initialize DENUE client Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb This code initializes the DENUE client from the INEGIpy library, requiring an API token. ```python from INEGIpy import DENUE token = "TuToken" denue = DENUE(token) ``` -------------------------------- ### Fetching Metadata Source: https://github.com/andreslomeliv/datosmex/blob/master/BANXICOpy/README.ipynb Retrieve metadata for specified indicators. ```python metadatos = bmx.metadatos(indicadores) metadatos ``` -------------------------------- ### Get Indicator Data with Metadata Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Retrieves indicator data along with metadata, displaying both the DataFrame head and the metadata. ```python df, metadatos = inegi.obtener_df(indicadores = "6200093954", nombres = 'poblacion_ocupada_aguascalientes', clave_area = '01', inicio = '2000', fin = '2010', metadatos = True) display(df.head()) display(metadatos) ``` -------------------------------- ### Get Indicator Data Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Retrieves indicator data for a specified period and displays the head and tail of the resulting DataFrame. ```python df = inegi.obtener_df(indicadores = ["289242","289242"], nombres = ['Indicador Coincidente', 'Indicador Adelantado'], inicio = '2000', fin = '2010') display(df.head()) display(df.tail()) ``` -------------------------------- ### Initialize MarcoGeoestadistico Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Initializes the MarcoGeoestadistico class. ```python from INEGIpy import MarcoGeoestadistico marco = MarcoGeoestadistico() ``` -------------------------------- ### Querying Series as Growth Rates Source: https://github.com/andreslomeliv/datosmex/blob/master/BANXICOpy/README.ipynb Fetch a series and specify the increment type, such as annual percentage growth. ```python # series como tasas de crecimiento base = bmx.obtener_series('SF44043', 'Base Monetaria', inicio = '2020', incremento='PorcAnual') base.head() ``` -------------------------------- ### Initialize DENUE Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Initializes the DENUE (Directorio Estadístico Nacional de Unidades Económicas) module with an API token. ```python from INEGIpy import DENUE token = 'TuToken' denue = DENUE(token) ``` -------------------------------- ### Initialize Indicadores with Token Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Initializes the Indicadores class with an API token. ```python from INEGIpy import Indicadores token = "92170321-528f-f1dd-5d59-f8613e072746" inegi = Indicadores(token) ``` -------------------------------- ### Get concatenated key for Monterrey and plot AGEBs Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb This snippet demonstrates how to retrieve the concatenated geographical key for Monterrey and then use it to fetch and plot the AGEBs (Ageoestadisticas Basicas) for that area. ```python cve_concatenada = nl_municipios[nl_municipios.nom_agem == 'Monterrey'].cvegeo.iloc[0] print('Clave Concatenada de Monterrey: {}'.format(cve_concatenada)) mty_agebs = marco.AGEBs(claves_concatenadas=cve_concatenada) mty_agebs.plot() ``` -------------------------------- ### Plotting municipalities and establishments in CDMX Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb This code uses the geostatistical framework to get the geographic area layer for plotting, specifically focusing on municipalities in CDMX and overlaying Zócalo and establishment data. ```python # utilizamos el marco geostadistico para obtener la capa del area geografica sobre la que plotear # Si no conoces la clave de alguna entidad, municipio o localidad la puedes buscar por nombre en el marco geoestadístico # regresa todas las manzanas en CDMX muns = marco.Municipios(entidades='09') ax = muns.plot(alpha = 0.5) zocalo.plot(ax=ax, color='yellow', zorder=2, markersize=20) estabs.plot(ax=ax, color='red', alpha=0.4) ``` -------------------------------- ### Inicializar clientes y obtener datos del PIB Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Ejemplo de cómo inicializar los clientes de Indicadores y MarcoGeoestadistico, y obtener el PIB real por entidad federativa. ```python token = 'TuToken' inegi = Indicadores(token) marco = MarcoGeoestadistico() indicadores = [str(i) for i in range(472080,472112)] # indicadores del PIB real por entidad federativa entidades = marco.Entidades() nombres = entidades.nom_agee.tolist() # nombres de las entidades pib_edos = inegi.obtener_df(indicadores = indicadores, nombres = nombres, inicio = '2019') display(pib_edos) ``` -------------------------------- ### Inicializar clientes para DENUE, MarcoGeoestadistico y Ruteo Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Inicializa las instancias de las clases DENUE, MarcoGeoestadistico y Ruteo con los tokens correspondientes. ```python from INEGIpy import DENUE, MarcoGeoestadistico, Ruteo import geopandas as gpd import pandas as pd ``` ```python token = 'TuToken' denue = DENUE(token) marco = MarcoGeoestadistico() token_ruteo = 'TuOtroToken' ruteo = Ruteo(token_ruteo) ``` -------------------------------- ### consulta_metadatos Method Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Retrieves metadata descriptions for one or more series. ```python Indicadores.consulta_metadatos(metadatos) ``` -------------------------------- ### Obtener Serie Method Source: https://github.com/andreslomeliv/datosmex/blob/master/BANXICOpy/README.md Method to obtain time series data for specified indicators. ```python Banxico.obtener_serie(indicadores, nombres = None, inicio = None, fin = None, decimales = True, incremento = None) ``` -------------------------------- ### Importar módulos Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Importación de los módulos necesarios para trabajar con indicadores y marco geoestadístico. ```python from INEGIpy import Indicadores, MarcoGeoestadistico ``` -------------------------------- ### Querying Multiple Series by Range Source: https://github.com/andreslomeliv/datosmex/blob/master/BANXICOpy/README.ipynb Fetch data for a range of series using a string representation of the range. ```python # varias series como un rango df = bmx.obtener_series('SF1-SF5') df.head() ``` -------------------------------- ### Calculate Routes and Apply Delay Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Iterates through a list of lines, calculates the optimal route for each using the CalcularRuta function, and applies a 30-second delay every 100 requests to manage potential API rate limits or long processing times. ```python import time rutas = [] for j in range(len(lineas_f)): r = ruteo.CalcularRuta(linea_i, lineas_f[j]) rutas.append(r) if j%100 == 0: time.sleep(30) len(rutas) ``` -------------------------------- ### Metadatos Method Source: https://github.com/andreslomeliv/datosmex/blob/master/BANXICOpy/README.md Method to obtain metadata for specified indicators. ```python Banxico.metadatos(indicadores) ``` -------------------------------- ### Calculate Percentage Changes Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Calculates the percentage change for each state's GDP using the `pct_change()` method and displays the result. ```python cambios_pcts = pib_edos.pct_change() display(cambios_pcts) ``` -------------------------------- ### catalogo_indicadores Method Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Retrieves a DataFrame with descriptions of indicators from a specified bank. ```python Indicadores.catalogo_indicadores(banco, indicador = None) ``` -------------------------------- ### Ruteo Class Initialization Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Initializes the Ruteo class with an INEGI token. ```python class INEGIpy.Ruteo(token) ``` -------------------------------- ### Obtener municipios de Nuevo León Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Este snippet muestra cómo obtener los municipios del estado de Nuevo León (entidad '19') y visualizar las primeras 10 filas del resultado. ```python nl_municipios = marco.Municipios(entidades='19') display(nl_municipios.head(10)) ``` -------------------------------- ### Fetch business details by ID and display Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb This code fetches detailed information for a specific business using its unique key ('993591') via the `denue.Ficha` method and displays the resulting DataFrame without converting it to a GeoDataFrame. ```python df = denue.Ficha(clave = '993591', as_geodf=False) display(df) ``` -------------------------------- ### Query Metadata Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Queries and displays the detailed description of the provided metadata. ```python desc_metadatos = inegi.consulta_metadatos(metadatos) display(desc_metadatos) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Imports the required modules from INEGIpy and other data science libraries. ```python from INEGIpy import DENUE, MarcoGeoestadistico, Ruteo import geopandas as gpd import pandas as pd ``` -------------------------------- ### Calculating routes to multiple destinations Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb This snippet demonstrates how to find the nearest street lines for multiple destination establishments and notes a potential issue with scale in the routing system. ```python # Para calcular una ruta se requiere la utilizar la función BuscarLinea (o BuscarDestino dependiendo de lo que se busca) con el fin de obtener la línea final de la ruta # Como tenemos varios puntos finales más bien sería una lista de líneas # Noté que en ocasiones el Sistema de Ruteo no encuentra información para una coordenada si la escala no está correcta por lo que aumenté el valor default de # la escala a 1,000,000 lo cual resolvió el problema para las coordenadas resultantes del DENUE sin embargo es importante tenerlo en cuenta para otras bases. lineas_f = [ruteo.BuscarLinea(estabs.Latitud.iloc[i], estabs.Longitud.iloc[i]) for i in range(estabs.shape[0])] len(lineas_f) ``` -------------------------------- ### Calcular y mostrar cambios porcentuales del PIB Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb Calcula la tasa de cambio porcentual del PIB por entidad federativa y muestra los resultados. ```python cambios_pcts = pib_edos.pct_change() display(cambios_pcts) ``` ```python cambios_pcts = cambios_pcts.stack().reset_index() cambios_pcts.columns = ['fechas','nom_agee','cambio_pct_pib_real'] display(cambios_pcts.head()) ``` ```python entidades = entidades.merge(cambios_pcts, how = 'left') entidades.cambio_pct_pib_real = entidades.cambio_pct_pib_real*100 display(entidades.head()) ``` ```python ax = entidades.plot(column = 'cambio_pct_pib_real', cmap = 'hot', legend = True, legend_kwds={'label':'Cambio (%)', 'orientation':"horizontal"}, figsize = (8,8), edgecolor = 'black', linewidth = 0.5) ax.set_title('Cambio Porcentual del PIB real por Entidad Federeativa \n 2019 - 2020') ax.set_axis_off() ``` -------------------------------- ### Search for establishments within a radius Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Uses the DENUE client to find establishments (filtered to 'oxxo') within a 5km radius of a given coordinate and plots them. ```python # utilizamos el DENUE para obtener una capa con los establecimientos en un radio de 5 km # inicié queriendo ver todos los establecimientos pero son demasiados para hacer buenos visuales así que acoté a solo los Oxxos lat, lng = zocalo.geometry.iloc[0].y, zocalo.geometry.iloc[0].x estabs = denue.Buscar('oxxo',lat,lng,5000) ax = zocalo.plot(color='yellow', zorder=2, markersize=50) estabs.plot(ax=ax, alpha=0.3, color='red', zorder=1) ``` -------------------------------- ### obtener_df Method Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Retrieves data for specified indicators as a pandas DataFrame. ```python Indicadores.obtener_df(indicadores, nombres = None, inicio = None, fin = None, banco = None, metadatos = False) ``` -------------------------------- ### Search for businesses by name and display results Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.ipynb This snippet searches for businesses with the name 'oxxo', limiting the results to the first 5 entries, and displays the resulting DataFrame without converting it to a GeoDataFrame. ```python df = denue.Nombre(nombre = 'oxxo', registro_final= 5, as_geodf=False) display(df) ``` -------------------------------- ### dato_oportuno() function signature Source: https://github.com/andreslomeliv/datosmex/blob/master/BANXICOpy/README.md Signature of the dato_oportuno function, detailing its parameters. ```python Banxico.dato_oportuno(indicadores, nombres = None, decimales = True incremento = None) ``` -------------------------------- ### Class Definition Source: https://github.com/andreslomeliv/datosmex/blob/master/BANXICOpy/README.ipynb The Banxico class requires a token provided by the Bank of Mexico. ```python class Banxico(token) ``` -------------------------------- ### DetalleRuta() Function Signature Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Shows the parameters for the DetalleRuta function, which calculates route details. ```python Ruteo.DetalleRuta(linea_inicial = None, linea_final = None, destino_inicial = None, destino_final = None, tipo_vehiculo = 0, ruta = 'optima', ejes_excedentes = 0, saltar_lineas = None, proyeccion = 'GRS80') ``` -------------------------------- ### Analyze and plot radial distances Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Calculates and prints the minimum, maximum, and mean radial distances of establishments. Then, it plots the municipalities, destination, and establishments, coloring them by radial distance. ```python # podemos ver que la distancia mínima son 300 metros, la máxima es cercana a los 5 km y la media es de 3.1 km estabs.distancia_radial.min(), estabs.distancia_radial.max(), estabs.distancia_radial.mean() ax = muns.plot(alpha = 0.5, figsize=(8,8)) zocalo.plot(ax=ax, color='yellow', zorder=2, markersize=20) estabs.plot(ax=ax, alpha=0.4, column='distancia_radial', legend = True, legend_kwds={'label':'Distancia (m)','orientation':"horizontal"}) ``` -------------------------------- ### Entidades Method Source: https://github.com/andreslomeliv/datosmex/blob/master/INEGIpy/README.md Retrieves state-level geoestatistical data. ```python MarcoGeoestadistico.Entidades(entidades = None, nombres = None, as_geodf = True) ```