Created
May 17, 2023 09:16
-
-
Save jfthuong/e3c030e6dc4a321f3742b5f48cd91a4a to your computer and use it in GitHub Desktop.
Getting Weather in DataFrame
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
from datetime import datetime | |
import pandas as pd | |
BREST = (48.39029, -4.4833) | |
NANTES = (47.218371, -1.553621) | |
DFLT_START = datetime(2018, 1, 1) | |
DFLT_END = datetime.today() | |
def get_weather_hourly_daily( | |
city: tuple[float, float], start: datetime = DFLT_START, end: datetime = DFLT_END | |
) -> tuple[pd.DataFrame, pd.DataFrame]: | |
"""Get Weather Data from Open-Meteo API for a given city""" | |
# Define the API endpoint and parameters | |
url = "https://archive-api.open-meteo.com/v1/era5" | |
hourly = [ | |
"temperature_2m", | |
"relativehumidity_2m", | |
"apparent_temperature", | |
# "precipitation_probability", # does not work | |
"precipitation", | |
] | |
daily = [ | |
"temperature_2m_max", | |
"temperature_2m_min", | |
"apparent_temperature_max", | |
"apparent_temperature_min", | |
] | |
params = { | |
"latitude": city[0], | |
"longitude": city[1], | |
"start_date": start.strftime("%Y-%m-%d"), | |
"end_date": end.strftime("%Y-%m-%d"), | |
"hourly": ",".join(hourly), | |
"daily": ",".join(daily), | |
"timezone": "Europe/Berlin", | |
} | |
# Send a GET request to the API and retrieve the data | |
response = requests.get(url, params=params) | |
print(response.status_code) | |
data = response.json() | |
# Convert the data to a Pandas DataFrame | |
# df = pd.DataFrame(data["forecast"]) | |
df_hourly = pd.DataFrame(data["hourly"]).dropna() | |
df_daily = pd.DataFrame(data["daily"]).dropna() | |
for df in (df_hourly, df_daily): | |
df["time"] = pd.to_datetime(df["time"]) | |
df["month"] = df.time.dt.month | |
df["year"] = df.time.dt.year | |
df.set_index("time", inplace=True) | |
df.rename(columns={c: c.replace("_2m", "") for c in df.columns}, inplace=True) | |
return df_hourly, df_daily | |
df_hourly, df_daily = get_weather_hourly_daily(BREST) | |
average_temp = df_daily.groupby(["month", "year"]).mean(numeric_only=True) | |
print(average_temp.describe()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment