Climate data plays a crucial role in several sectors, assisting in studies and forecasts that impact areas such as agriculture, urban planning, and natural resource management.
The National Institute of Meteorology (INMET) offers the Meteorological Database (BDMEP) on its website monthly. This database contains a historical series of climate information collected by hundreds of measuring stations distributed throughout Brazil. In BDMEP, you will find detailed data on rainfall, temperature, air humidity and wind speed.
With hourly updates, this data is quite voluminous, providing a rich basis for detailed analysis and informed decision making.
In this post I will show how to collect and process climate data from INMET-BDMEP. We will collect the raw data files available on the INMET website and then process this data to facilitate analysis.
1. Required Python Packages
To achieve the aforementioned objectives, you will only need to have installed three packages:
httpx to make HTTP requests
Pandas for reading and processing data
tqdm to show a friendly progress bar in the terminal while the program downloads or reads files
To install the necessary packages, run the following command in the terminal:
1
pip install httpx pandas tqdm
Salin selepas log masuk
If you are using a virtual environment (venv) with poetry, for example, use the following command:
1
poetry add httpx pandas tqdm
Salin selepas log masuk
2. Collection of files
2.1 File URL pattern
The address of BDMEP data files follows a very simple pattern. The pattern is as follows:
The only part that changes is the file name, which is simply the reference year of the data. Monthly, the file for the most recent (current) year is replaced with updated data.
This makes it easy to create code to automatically collect data files from all available years.
In fact, the historical series available begins in the year 2000.
2.2 Collection strategy
To collect data files from INMET-BDMEP we will use the httpx library to make HTTP requests and the tqdm library to show a friendly progress bar in the terminal.
First, let's import the necessary packages:
1
2
3
4
5
import datetime asdt
from pathlib import Path
import httpx
from tqdm import tqdm
Salin selepas log masuk
We have already identified the URL pattern of the INMET-BDMEP data files. Now let's create a function that accepts a year as an argument and returns the URL of the file for that year.
To check whether the URL file has been updated, we can use the information present in the header returned by an HTTP request. On well-configured servers, we can request just this header with the HEAD method. In this case, the server was well configured and we can use this method.
The response to the HEAD request will have the following format:
1
Mon, 01 Sep 2024 00:01:00 GMT
Salin selepas log masuk
To parse this date/time I created the following function in Python, which accepts a string and returns a datetime object:
So, we can use the date/time of the last modification to include it in the name of the file we are going to download, using string interpolation (f-strings):
This way, you can easily check whether the file with the most recent data already exists on our local file system. If the file already exists, the program can be terminated; otherwise, we must proceed with collecting the file, making the request to the server.
The download_year function below downloads the file for a specific year. If the file already exists in the destination directory, the function simply returns without doing anything.
Note how we use tqdm to show a friendly progress bar in the terminal while the file is downloaded.
Now that we have all the necessary functions, we can collect the INMET-BDMEP data files.
Using a for loop we can download the files for all available years. The following code does exactly that. Starting from the year 2000 to the current year.
1
2
3
destdirpath = Path("data")
foryear in range(2000, dt.datetime.now().year + 1):
download_year(year, destdirpath)
Salin selepas log masuk
3. Reading and processing of data
With the INMET-BDMEP raw data files downloaded, we can now read and process the data.
Let's import the necessary packages:
1
2
3
4
5
6
7
8
9
10
import csv
import datetime asdt
import io
import re
import zipfile
from pathlib import Path
import numpy asnp
import pandas aspd
from tqdm import tqdm
Salin selepas log masuk
3.1 File structure
Inside the ZIP file provided by INMET we find several CSV files, one for each weather station.
Porém, nas primeiras linhas desses arquivos CSV encontramos informações sobre a estação, como a região, a unidade federativa, o nome da estação, o código WMO, as coordenadas geográficas (latitude e longitude), a altitude e a data de fundação. Vamos extrair essas informações para usar como metadados.
3.2 Leitura dos dados com pandas
A leitura dos arquivos será feita em duas partes: primeiro, será feita a leitura dos metadados das estações meteorológicas; depois, será feita a leitura dos dados históricos propriamente ditos.
3.2.1 Metadados
Para extrair os metadados nas primeiras 8 linhas do arquivo CSV vamos usar o pacote embutido csv do Python.
Para entender a função a seguir é necessário ter um conhecimento um pouco mais avançado de como funciona handlers de arquivos (open), iteradores (next) e expressões regulares (re.match).
Em resumo, a função read_metadata definida acima lê as primeiras oito linhas do arquivo, processa os dados e retorna um dicionário com as informações extraídas.
3.2.2 Dados históricos
Aqui, finalmente, veremos como fazer a leitura do arquivo CSV. Na verdade é bastante simples. Basta usar a função read_csv do Pandas com os argumentos certos.
A seguir está exposto a chamada da função com os argumentos que eu determinei para a correta leitura do arquivo.
1
2
3
4
5
6
7
8
9
pd.read_csv(
"arquivo.csv",
sep=";",
decimal=",",
na_values="-9999",
encoding="latin-1",
skiprows=8,
usecols=range(19),
)
Salin selepas log masuk
Primeiro é preciso dizer que o caractere separador das colunas é o ponto-e-vírgula (;), o separador de número decimal é a vírgula (,) e o encoding é latin-1, muito comum no Brasil.
Também é preciso dizer para pular as 8 primeiras linhas do arquivo (skiprows=8), que contém os metadados da estação), e usar apenas as 19 primeiras colunas (usecols=range(19)).
Por fim, vamos considerar o valor -9999 como sendo nulo (na_values="-9999").
3.3 Tratamento dos dados
Os nomes das colunas dos arquivos CSV do INMET-BDMEP são bem descritivos, mas um pouco longos. E os nomes não são consistentes entre os arquivos e ao longo do tempo. Vamos renomear as colunas para padronizar os nomes e facilitar a manipulação dos dados.
A seguinte função será usada para renomear as colunas usando expressões regulares (RegEx):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def columns_renamer(name: str) -> str:
name = name.lower()
ifre.match(r"data", name):
return"data"
ifre.match(r"hora", name):
return"hora"
ifre.match(r"precipita[çc][ãa]o", name):
return"precipitacao"
ifre.match(r"press[ãa]o atmosf[ée]rica ao n[íi]vel", name):
ifre.match(r"temperatura do ponto de orvalho", name):
return"temperatura_orvalho"
ifre.match(r"temperatura m[áa]x", name):
return"temperatura_maxima"
ifre.match(r"temperatura m[íi]n", name):
return"temperatura_minima"
ifre.match(r"temperatura orvalho m[áa]x", name):
return"temperatura_orvalho_maxima"
ifre.match(r"temperatura orvalho m[íi]n", name):
return"temperatura_orvalho_minima"
ifre.match(r"umidade rel\. m[áa]x", name):
return"umidade_relativa_maxima"
ifre.match(r"umidade rel\. m[íi]n", name):
return"umidade_relativa_minima"
ifre.match(r"umidade relativa do ar", name):
return"umidade_relativa"
ifre.match(r"vento, dire[çc][ãa]o", name):
return"vento_direcao"
ifre.match(r"vento, rajada", name):
return"vento_rajada"
ifre.match(r"vento, velocidade", name):
return"vento_velocidade"
Salin selepas log masuk
Agora que temos os nomes das colunas padronizados, vamos tratar a data/hora. Os arquivos CSV do INMET-BDMEP têm duas colunas separadas para data e hora. Isso é inconveniente, pois é mais prático ter uma única coluna de data/hora. Além disso existem inconsistências nos horários, que às vezes têm minutos e às vezes não.
As três funções a seguir serão usadas para criar uma única coluna de data/hora:
Existe um problema com os dados do INMET-BDMEP que é a presença de linhas vazias. Vamos remover essas linhas vazias para evitar problemas futuros. O código a seguir faz isso:
Tem um problema com a função acima. Ela não lida com arquivos ZIP.
Criamos, então, a função read_zipfile para a leitura de todos os arquivos contidos no arquivo ZIP. Essa função itera sobre todos os arquivos CSV no arquivo zipado, faz a leitura usando a função read_data e os metadados usando a função read_metadata, e depois junta os dados e os metadados em um único DataFrame.
1
2
3
4
5
6
7
8
9
10
def read_zipfile(filepath: Path) -> pd.DataFrame:
data = pd.DataFrame()
with zipfile.ZipFile(filepath) asz:
files = [zf forzf in z.infolist() ifnot zf.is_dir()]
forzf in tqdm(files):
d = read_data(z.open(zf.filename))
meta = read_metadata(z.open(zf.filename))
d = d.assign(**meta)
data = pd.concat((data, d), ignore_index=True)
returndata
Salin selepas log masuk
No final, basta usar essa última função definida (read_zipfile) para fazer a leitura dos arquivos ZIP baixados do site do INMET. (. ❛ ᴗ ❛.)
Temperatura horária e média diária em São Paulo em 2023
5. Conclusão
Neste texto mostrei como coletar e tratar os dados climáticos do INMET-BDMEP. Os dados coletados são muito úteis para estudos e previsões nas mais variadas áreas. Com os dados tratados, é possível fazer análises e gráficos como o que mostrei no final.
Espero que tenha gostado do texto e que tenha sido útil para você.
Saya mencipta pakej Python dengan fungsi yang saya tunjukkan dalam teks ini. Pakej ini tersedia dalam repositori Git saya. Jika anda mahu, anda boleh memuat turun pakej dan menggunakan fungsi dalam kod anda sendiri.
Atas ialah kandungan terperinci Mengumpul dan Memproses Data Iklim INMET-BDMPEP. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn