### Install supported Python versions Source: https://github.com/alantaranti/sidrapy/blob/master/CONTRIBUTING.md Uses pyenv to install multiple Python versions required for testing. ```shell $ PY_VERSIONS=`pyenv install -l | awk '{$1=$1};1' | egrep -v '(-|r|^2|^3\.[0-6]\.)' | tac | sort -u -t'.' -k2,2` $ echo $PY_VERSIONS | xargs -n1 pyenv install ``` -------------------------------- ### Install sidrapy via pip Source: https://github.com/alantaranti/sidrapy/blob/master/README.md Use this command to install or update the library in your Python environment. ```shell pip install -U sidrapy ``` -------------------------------- ### Instalar dependências de desenvolvimento Source: https://github.com/alantaranti/sidrapy/blob/master/CONTRIBUTING.md Instala o pacote no modo editável junto com as dependências listadas no arquivo de desenvolvimento. ```shell $ pip install -e . -r requirements/development.txt ``` -------------------------------- ### Instalar hooks do pre-commit Source: https://github.com/alantaranti/sidrapy/blob/master/CONTRIBUTING.md Configura os hooks do Git para garantir a formatação do código antes de cada commit. ```shell $ pre-commit install ``` -------------------------------- ### Adicionar fork como repositório remoto Source: https://github.com/alantaranti/sidrapy/blob/master/CONTRIBUTING.md Configura o repositório do usuário como um remoto chamado 'fork' para facilitar o envio de alterações. ```shell $ git remote add fork https://github.com/{usuario}/sidrapy ``` -------------------------------- ### Execute full test suite with tox Source: https://github.com/alantaranti/sidrapy/blob/master/CONTRIBUTING.md Configures local Python versions and runs the full test suite via tox. ```shell $ PY_VERSIONS=`pyenv versions | awk '{$1=$1};1' | egrep -v '(-|r|^2|^3\.[0-6]\.)'` $ echo $PY_VERSIONS | xargs pyenv local $ tox ``` -------------------------------- ### Clonar o repositório sidrapy Source: https://github.com/alantaranti/sidrapy/blob/master/CONTRIBUTING.md Baixa o código-fonte do projeto e entra no diretório criado. ```shell $ git clone https://github.com/AlanTaranti/sidrapy $ cd sidrapy ``` -------------------------------- ### get_table() Parameters Reference Source: https://context7.com/alantaranti/sidrapy/llms.txt A comprehensive reference of all available parameters for the `get_table()` function, detailing their types, requirements, and descriptions. ```APIDOC ## GET /api/data/get_table ### Description Provides a detailed reference for all parameters accepted by the `get_table()` function. ### Method GET ### Endpoint /api/data/get_table ### Parameters #### Query Parameters - **table_code** (str) - Required - Código da tabela no SIDRA. - **territorial_level** (str) - Required - Nível territorial (1=Brasil, 2=Região, 3=UF, etc.). - **ibge_territorial_code** (str) - Required - Código territorial ("all" para todos, ou código específico). - **variable** (str) - Optional - Variáveis desejadas (padrão: todas exceto percentuais). - **classification** (str) - Optional - Código de uma classificação única. - **categories** (str) - Optional - Categorias da classificação (separadas por vírgula). - **classifications** (Dict[str, str]) - Optional - Múltiplas classificações {código: categorias}. - **period** (str) - Optional - Período ("last 12", "2018", "202002", etc.). - **header** (str) - Optional - Incluir cabeçalho: "y" (sim) ou "n" (não). - **format** (str) - Optional - Formato de saída: "pandas" (padrão) ou "list". ### Request Example ```python import sidrapy data = sidrapy.get_table( table_code="1419", territorial_level="1", ibge_territorial_code="all", variable="63", period="last 6", header="y", format="pandas" ) ``` ### Response #### Success Response (200) - **Documentation** - Detailed information about each parameter. #### Response Example (This section describes the parameters, not a typical API response body.) ``` -------------------------------- ### Criar e ativar ambiente virtual Source: https://github.com/alantaranti/sidrapy/blob/master/CONTRIBUTING.md Cria e ativa um ambiente virtual Python para isolar as dependências do projeto. ```shell $ python3 -m venv venv $ . venv/bin/activate ``` ```shell > env\Scripts\activate ``` -------------------------------- ### Criar branch para novos recursos Source: https://github.com/alantaranti/sidrapy/blob/master/CONTRIBUTING.md Cria uma nova branch baseada na branch de desenvolvimento para novas funcionalidades. ```shell $ git fetch origin $ git checkout -b your-branch-name origin/develop ``` -------------------------------- ### get_table() with Pandas DataFrame Output Source: https://context7.com/alantaranti/sidrapy/llms.txt Demonstrates how to retrieve data in a Pandas DataFrame format, which is the default and facilitates data analysis and manipulation. ```APIDOC ## GET /api/data/get_table ### Description Retrieves data from a SIDRA table and returns it as a Pandas DataFrame. ### Method GET ### Endpoint /api/data/get_table ### Parameters #### Query Parameters - **table_code** (str) - Required - The code of the table in SIDRA. - **territorial_level** (str) - Required - The territorial level (e.g., '1' for Brazil, '2' for Region). - **ibge_territorial_code** (str) - Required - The IBGE territorial code ('all' for all, or a specific code). - **period** (str) - Required - The period for the data (e.g., '2018', 'last 6'). - **variable** (str) - Optional - Specifies the desired variables (e.g., 'allxp' for all except percentages). - **header** (str) - Optional - Controls whether the header row is included ('y' for yes, 'n' for no). Defaults to 'y'. - **format** (str) - Optional - The output format ('pandas' or 'list'). Defaults to 'pandas'. ### Request Example ```python import sidrapy data = sidrapy.get_table( table_code="1612", territorial_level="1", ibge_territorial_code="1", period="2018", variable="allxp", header="y", format="pandas" ) print(data.columns.tolist()) ``` ### Response #### Success Response (200) - **DataFrame** - A Pandas DataFrame containing the requested data. #### Response Example ```python # Example output of data.columns.tolist() # ['NC', 'NN', 'MC', 'MN', 'V', 'D1C', 'D1N', 'D2C', 'D2N', 'D3C', 'D3N', 'D4C', 'D4N'] # Example of filtered data # print(area_plantada[['D1N', 'V', 'MN']]) # D1N V MN # 1 2018 73274337 Hectares ``` ``` -------------------------------- ### Utilizar todos os parâmetros da função get_table Source: https://context7.com/alantaranti/sidrapy/llms.txt Exemplo de consulta configurando múltiplos filtros como período, variável e nível territorial. ```python import sidrapy # Exemplo usando todos os parâmetros data = sidrapy.get_table( table_code="1419", # Tabela do IPCA territorial_level="1", # Brasil ibge_territorial_code="all", # Todas as unidades variable="63", # Variação mensal period="last 6", # Últimos 6 períodos header="y", # Com cabeçalho format="pandas" # Como DataFrame ) ``` -------------------------------- ### Generate test coverage report Source: https://github.com/alantaranti/sidrapy/blob/master/CONTRIBUTING.md Runs tests with coverage tracking and generates an HTML report. ```shell $ coverage run -m pytest $ coverage html ``` -------------------------------- ### Enviar alterações para o fork Source: https://github.com/alantaranti/sidrapy/blob/master/CONTRIBUTING.md Publica a branch local no repositório remoto do usuário no GitHub. ```shell $ git push --set-upstream fork your-branch-name ``` -------------------------------- ### sidrapy.get_table() - Basic Usage Source: https://context7.com/alantaranti/sidrapy/llms.txt Fetches data from a SIDRA table with basic parameters like table code, territorial level, and period. ```APIDOC ## GET /api/sidrapy/table ### Description Fetches data from a SIDRA table using its code, territorial level, and period. ### Method GET ### Endpoint /api/sidrapy/table ### Parameters #### Query Parameters - **table_code** (string) - Required - The code of the SIDRA table to query. - **territorial_level** (string) - Required - The desired territorial level (e.g., '1' for Brazil). - **ibge_territorial_code** (string) - Required - The IBGE territorial code (e.g., 'all' for all available units). - **period** (string) - Optional - The period for which to retrieve data (e.g., 'last 12', '2023'). - **format** (string) - Optional - The desired output format ('dataframe' or 'list'). Defaults to 'dataframe'. ### Request Example ```python import sidrapy data = sidrapy.get_table( table_code="1419", territorial_level="1", ibge_territorial_code="all", period="last 12" ) print(data.head()) ``` ### Response #### Success Response (200) - **data** (DataFrame or list) - The retrieved statistical data. #### Response Example ```json { "data": [ { "NC": "1", "NN": "Brasil", "MC": "1004", "MN": "Mês do ano (Código)", "V": "1.05", "D1C": "202301", "D1N": "janeiro 2023" }, { "NC": "1", "NN": "Brasil", "MC": "1004", "MN": "Mês do ano (Código)", "V": "0.73", "D1C": "202302", "D1N": "fevereiro 2023" } ] } ``` ``` -------------------------------- ### Run basic tests with pytest Source: https://github.com/alantaranti/sidrapy/blob/master/CONTRIBUTING.md Executes the basic test suite in the current environment. ```shell $ pytest ``` -------------------------------- ### Obter dados como Pandas DataFrame Source: https://context7.com/alantaranti/sidrapy/llms.txt Utiliza o formato padrão para facilitar a manipulação de dados estatísticos com pandas. ```python import sidrapy import pandas as pd # Obter dados de produção agrícola como DataFrame # Tabela 1612 = Área plantada, área colhida, quantidade produzida, # rendimento médio e valor da produção das lavouras temporárias data = sidrapy.get_table( table_code="1612", territorial_level="1", ibge_territorial_code="1", period="2018", variable="allxp", # Todas as variáveis exceto percentuais header="y", # Incluir cabeçalho format="pandas" # Formato DataFrame (padrão) ) # Manipular dados com pandas print(data.columns.tolist()) # ['NC', 'NN', 'MC', 'MN', 'V', 'D1C', 'D1N', 'D2C', 'D2N', 'D3C', 'D3N', 'D4C', 'D4N'] # Filtrar apenas área plantada area_plantada = data[data['D2N'] == 'Área plantada'] print(area_plantada[['D1N', 'V', 'MN']]) # D1N V MN # 1 2018 73274337 Hectares ``` -------------------------------- ### Configurar usuário e email no Git Source: https://github.com/alantaranti/sidrapy/blob/master/CONTRIBUTING.md Define as credenciais globais do Git necessárias para identificar o autor dos commits. ```shell $ git config --global user.name 'your name' $ git config --global user.email 'your email' ``` -------------------------------- ### Criar branch para correção de bug Source: https://github.com/alantaranti/sidrapy/blob/master/CONTRIBUTING.md Cria uma nova branch baseada na versão estável para correções de bugs ou documentação. ```shell $ git fetch origin $ git checkout -b your-branch-name origin/0.1.x ``` -------------------------------- ### Fetch Data with get_table Source: https://context7.com/alantaranti/sidrapy/llms.txt Retrieve statistical data from the SIDRA API as a pandas DataFrame. ```python import sidrapy # Exemplo básico: Obter dados do IPCA dos últimos 12 meses # Tabela 1419 = IPCA - Variação mensal, acumulada no ano, acumulada em 12 meses # Nível territorial 1 = Brasil # ibge_territorial_code "all" = Todas as unidades territoriais disponíveis data = sidrapy.get_table( table_code="1419", territorial_level="1", ibge_territorial_code="all", period="last 12" ) # Resultado: DataFrame pandas com dados do IPCA print(data.head()) # NC NN MC MN V D1C D1N ... # 0 1 Brasil 1004 Mês do ano (Código) ... 202301 janeiro 2023 ... # 1 1 Brasil 1004 Mês do ano (Código) ... 202302 fevereiro 2023 ... ``` -------------------------------- ### Estrutura e manipulação da resposta da API Source: https://context7.com/alantaranti/sidrapy/llms.txt Demonstra como acessar os metadados e valores de uma resposta retornada no formato de lista. ```python # Campos comuns na resposta: # NC = Nível Territorial (Código) # NN = Nível Territorial (Nome) # MC = Unidade de Medida (Código) # MN = Unidade de Medida (Nome) # V = Valor # D1C, D2C, ... = Dimensões (Códigos) # D1N, D2N, ... = Dimensões (Nomes) import sidrapy data = sidrapy.get_table( table_code="1612", territorial_level="1", ibge_territorial_code="1", period="2018", format="list" ) # Primeira linha é o cabeçalho (quando header='y') cabecalho = data[0] print(cabecalho) # { # 'NC': 'Nível Territorial (Código)', # 'NN': 'Nível Territorial', # 'MC': 'Unidade de Medida (Código)', # 'MN': 'Unidade de Medida', # 'V': 'Valor', # 'D1C': 'Ano (Código)', # 'D1N': 'Ano', # 'D2C': 'Variável (Código)', # 'D2N': 'Variável', # 'D3C': 'Brasil (Código)', # 'D3N': 'Brasil', # 'D4C': 'Produto das lavouras temporárias (Código)', # 'D4N': 'Produto das lavouras temporárias' # } # Segunda linha em diante são os dados registro = data[1] print(f"Ano: {registro['D1N']}") print(f"Variável: {registro['D2N']}") print(f"Valor: {registro['V']} {registro['MN']}") # Ano: 2018 # Variável: Área plantada # Valor: 73274337 Hectares ``` -------------------------------- ### Obter dados sem cabeçalho Source: https://context7.com/alantaranti/sidrapy/llms.txt Define o parâmetro header como 'n' para omitir a linha de descrição dos campos no resultado. ```python import sidrapy # Obter dados sem linha de cabeçalho data = sidrapy.get_table( table_code="5459", territorial_level="1", ibge_territorial_code="all", classifications={"11278": "33460", "166": "3067,3327"}, period="202002", header="n", # Não incluir cabeçalho format="list" ) # Resultado: Lista começando diretamente com os dados # Sem a primeira linha de descrição dos campos print(data[0]) # { # 'D1C': '1', # 'D1N': 'Brasil', # 'D2C': '202002', # 'D2N': '2º semestre 2020', # 'D3C': '33460', # 'D3N': 'menos de 1.200 toneladas', # 'D4C': '3067', # 'D4N': 'Armazéns graneleiros e granelizados', # 'D5C': '152', # 'D5N': 'Número de estabelecimentos', # 'MC': '1020', # 'MN': 'Unidades', # 'NC': '1', # 'NN': 'Brasil', # 'V': '185' # } ``` -------------------------------- ### sidrapy.get_table() - With Multiple Classifications Source: https://context7.com/alantaranti/sidrapy/llms.txt Fetches data by specifying multiple classifications and their respective categories using a dictionary. ```APIDOC ## GET /api/sidrapy/table/multi-classified ### Description Fetches data from a SIDRA table using multiple classifications and categories specified in a dictionary. ### Method GET ### Endpoint /api/sidrapy/table/multi-classified ### Parameters #### Query Parameters - **table_code** (string) - Required - The code of the SIDRA table. - **territorial_level** (string) - Required - The desired territorial level. - **ibge_territorial_code** (string) - Required - The IBGE territorial code. - **classifications** (object) - Required - A dictionary where keys are classification codes and values are comma-separated category codes. - **period** (string) - Optional - The period for data retrieval. - **format** (string) - Optional - The output format ('dataframe' or 'list'). Defaults to 'dataframe'. ### Request Example ```python import sidrapy data = sidrapy.get_table( table_code="5459", territorial_level="1", ibge_territorial_code="all", classifications={ "11278": "33460", "166": "3067,3327" }, period="202002", format="list" ) print(data) ``` ### Response #### Success Response (200) - **data** (DataFrame or list) - The statistical data filtered by multiple classifications. #### Response Example ```json { "data": [ { "D1C": "Brasil (Código)", "D1N": "Brasil", "D3C": "Grupos de capacidade útil (Código)", "D3N": "Grupos de capacidade útil", "D4C": "Tipo de unidade armazenadora (Código)", "D4N": "Tipo de unidade armazenadora" }, { "D1C": "1", "D1N": "Brasil", "D3C": "33460", "D3N": "menos de 1.200 toneladas", "D4C": "3067", "D4N": "Armazéns graneleiros e granelizados", "V": "185" } ] } ``` ``` -------------------------------- ### sidrapy.get_table() - With Specific Classification Source: https://context7.com/alantaranti/sidrapy/llms.txt Fetches data by specifying a unique classification and its category for more granular results. ```APIDOC ## GET /api/sidrapy/table/classified ### Description Fetches data from a SIDRA table, filtering by a specific classification and category. ### Method GET ### Endpoint /api/sidrapy/table/classified ### Parameters #### Query Parameters - **table_code** (string) - Required - The code of the SIDRA table. - **territorial_level** (string) - Required - The desired territorial level. - **ibge_territorial_code** (string) - Required - The IBGE territorial code. - **classification** (string) - Required - The code of the classification to filter by. - **categories** (string) - Required - The category code(s) within the classification. - **period** (string) - Optional - The period for data retrieval. - **format** (string) - Optional - The output format ('dataframe' or 'list'). Defaults to 'dataframe'. ### Request Example ```python import sidrapy data = sidrapy.get_table( table_code="5459", territorial_level="1", ibge_territorial_code="all", classification="11278", categories="39324", period="202002", format="list" ) print(data) ``` ### Response #### Success Response (200) - **data** (DataFrame or list) - The filtered statistical data. #### Response Example ```json { "data": [ { "NC": "Nível Territorial (Código)", "NN": "Nível Territorial", "MC": "Unidade de Medida (Código)", "MN": "Unidade de Medida", "V": "Valor", "D1C": "202301", "D1N": "janeiro 2023" }, { "NC": "1", "NN": "Brasil", "MC": "1020", "MN": "Unidades", "V": "6731", "D2C": "202002", "D2N": "2º semestre 2020", "D3C": "39324", "D3N": "Total" } ] } ``` ``` -------------------------------- ### get_table() without Header Source: https://context7.com/alantaranti/sidrapy/llms.txt Illustrates how to fetch data without the header row by setting the `header` parameter to 'n'. This is useful when only the data itself is needed. ```APIDOC ## GET /api/data/get_table ### Description Retrieves data from a SIDRA table without including the header row. ### Method GET ### Endpoint /api/data/get_table ### Parameters #### Query Parameters - **table_code** (str) - Required - The code of the table in SIDRA. - **territorial_level** (str) - Required - The territorial level. - **ibge_territorial_code** (str) - Required - The IBGE territorial code ('all' or specific). - **classifications** (Dict[str, str]) - Optional - Multiple classifications in the format {code: categories}. - **period** (str) - Required - The period for the data. - **header** (str) - Optional - Set to 'n' to exclude the header row. - **format** (str) - Optional - The output format ('pandas' or 'list'). Defaults to 'pandas'. ### Request Example ```python import sidrapy data = sidrapy.get_table( table_code="5459", territorial_level="1", ibge_territorial_code="all", classifications={"11278": "33460", "166": "3067,3327"}, period="202002", header="n", format="list" ) print(data[0]) ``` ### Response #### Success Response (200) - **list** - A list of dictionaries, where each dictionary represents a data record. The first element is the first data record, as the header is omitted. #### Response Example ```json { "D1C": "1", "D1N": "Brasil", "D2C": "202002", "D2N": "2º semestre 2020", "D3C": "33460", "D3N": "menos de 1.200 toneladas", "D4C": "3067", "D4N": "Armazéns graneleiros e granelizados", "D5C": "152", "D5N": "Número de estabelecimentos", "MC": "1020", "MN": "Unidades", "NC": "1", "NN": "Brasil", "V": "185" } ``` ``` -------------------------------- ### Fetch IPCA data with sidrapy Source: https://github.com/alantaranti/sidrapy/blob/master/README.md Retrieve statistical data by specifying the table code, territorial level, and time period. ```python import sidrapy data = sidrapy.get_table(table_code="1419", territorial_level="1", ibge_territorial_code="all", period="last 12") ``` -------------------------------- ### API Response Structure Source: https://context7.com/alantaranti/sidrapy/llms.txt Explains the common fields and structure of the data returned by the SIDRA API, including codes and names for different dimensions. ```APIDOC ## API Response Structure ### Description Details the standard structure of data returned by the SIDRA API, including common fields for territorial levels, units of measure, and dimensions. ### Common Fields - **NC**: Nível Territorial (Código) - **NN**: Nível Territorial (Nome) - **MC**: Unidade de Medida (Código) - **MN**: Unidade de Medida (Nome) - **V**: Valor - **D1C, D2C, ...**: Dimensões (Códigos) - **D1N, D2N, ...**: Dimensões (Nomes) ### Response Example (List Format) ```python import sidrapy data = sidrapy.get_table( table_code="1612", territorial_level="1", ibge_territorial_code="1", period="2018", format="list" ) # Header row (when header='y') cabecalho = data[0] print(cabecalho) # { # 'NC': 'Nível Territorial (Código)', # 'NN': 'Nível Territorial', # 'MC': 'Unidade de Medida (Código)', # 'MN': 'Unidade de Medida', # 'V': 'Valor', # 'D1C': 'Ano (Código)', # 'D1N': 'Ano', # 'D2C': 'Variável (Código)', # 'D2N': 'Variável', # 'D3C': 'Brasil (Código)', # 'D3N': 'Brasil', # 'D4C': 'Produto das lavouras temporárias (Código)', # 'D4N': 'Produto das lavouras temporárias' # } # Data record registro = data[1] print(f"Ano: {registro['D1N']}") print(f"Variável: {registro['D2N']}") print(f"Valor: {registro['V']} {registro['MN']}") # Ano: 2018 # Variável: Área plantada # Valor: 73274337 Hectares ``` ``` -------------------------------- ### Fetch Data with Multiple Classifications Source: https://context7.com/alantaranti/sidrapy/llms.txt Perform complex queries by passing a dictionary of classifications and categories. ```python import sidrapy # Obter dados com múltiplas classificações # Classificação 11278 = Grupos de capacidade útil (categoria 33460 = menos de 1.200 toneladas) # Classificação 166 = Tipo de unidade armazenadora (categorias 3067 e 3327) data = sidrapy.get_table( table_code="5459", territorial_level="1", ibge_territorial_code="all", classifications={"11278": "33460", "166": "3067,3327"}, period="202002", format="list" ) # Resultado esperado: # [ # { # "D1C": "Brasil (Código)", # "D1N": "Brasil", # "D2C": "Semestre (Código)", # "D2N": "Semestre", # "D3C": "Grupos de capacidade útil (Código)", # "D3N": "Grupos de capacidade útil", # "D4C": "Tipo de unidade armazenadora (Código)", # "D4N": "Tipo de unidade armazenadora", # ... # }, # { # "D1C": "1", # "D1N": "Brasil", # "D2C": "202002", # "D2N": "2º semestre 2020", # "D3C": "33460", # "D3N": "menos de 1.200 toneladas", # "D4C": "3067", # "D4N": "Armazéns graneleiros e granelizados", # "D5C": "152", # "D5N": "Número de estabelecimentos", # "V": "185", # ... # }, # ... # ] ``` -------------------------------- ### Fetch Data with Single Classification Source: https://context7.com/alantaranti/sidrapy/llms.txt Filter data using a specific classification and category, returning the result as a list. ```python import sidrapy # Obter dados de capacidade de armazenamento agrícola # Tabela 5459 = Capacidade útil dos estabelecimentos agropecuários # Classificação 11278 = Grupos de capacidade útil # Categoria 39324 = Total data = sidrapy.get_table( table_code="5459", territorial_level="1", ibge_territorial_code="all", classification="11278", categories="39324", period="202002", format="list" ) # Resultado esperado (formato lista): # [ # { # "NC": "Nível Territorial (Código)", # "NN": "Nível Territorial", # "MC": "Unidade de Medida (Código)", # "MN": "Unidade de Medida", # "V": "Valor", # ... # }, # { # "NC": "1", # "NN": "Brasil", # "MC": "1020", # "MN": "Unidades", # "V": "6731", # "D2C": "202002", # "D2N": "2º semestre 2020", # "D3C": "39324", # "D3N": "Total", # "D4C": "152", # "D4N": "Número de estabelecimentos", # ... # }, # ... # ] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.