Datasets:
File size: 4,771 Bytes
e3657eb |
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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
import requests
from datetime import datetime, timedelta
import pandas as pd
class WeatherDataFetcher:
def __init__(self, api_key):
self.api_key = api_key
def get_lat_lon(self, city_name):
"""
Fetches the latitude and longitude for a given city name.
Parameters:
- city_name: The name of the city (including state and country).
Returns:
- A tuple (latitude, longitude) if successful, None otherwise.
"""
url = f'http://api.openweathermap.org/geo/1.0/direct?q={city_name}&limit=1&appid={self.api_key}'
try:
response = requests.get(url)
data = response.json()
if data:
return data[0]['lat'], data[0]['lon']
else:
print('No geo data found')
return None
except Exception as e:
print(f"Error fetching geo data: {e}")
return None
def fetch_weather_data(self, lat, lon, start_date, end_date):
"""
Fetches weather data for a given set of coordinates within a specified date range
and adds latitude and longitude to the DataFrame.
Parameters:
- lat: Latitude of the location.
- lon: Longitude of the location.
- start_date: The start date as a datetime object.
- end_date: The end date as a datetime object.
Returns:
- A pandas DataFrame containing the weather data along with latitude and longitude.
"""
daily_data_frames = []
current_date = start_date
while current_date <= end_date:
timestamp = int(datetime.timestamp(current_date))
url = f'https://history.openweathermap.org/data/2.5/history/city?lat={lat}&lon={lon}&type=hour&start={timestamp}&appid={self.api_key}'
response = requests.get(url)
if response.status_code == 200:
data = response.json()
if 'list' in data:
df_day = pd.json_normalize(data['list'])
# Add latitude and longitude as columns
df_day['latitude'] = lat
df_day['longitude'] = lon
df_day['date'] = current_date.strftime('%Y-%m-%d')
daily_data_frames.append(df_day)
else:
print(f"No 'list' key found in data for {current_date.strftime('%Y-%m-%d')}")
else:
print(f"Failed to retrieve data for {current_date.strftime('%Y-%m-%d')} with status code {response.status_code}")
current_date += timedelta(days=1)
if daily_data_frames:
df_all_days = pd.concat(daily_data_frames, ignore_index=True)
return self.expand_weather_column(df_all_days)
else:
return pd.DataFrame()
def expand_weather_column(self,df):
# Check if 'weather' column exists
if 'weather' in df.columns:
# Extract weather details
df['weather_id'] = df['weather'].apply(lambda x: x[0]['id'] if x else None)
df['weather_main'] = df['weather'].apply(lambda x: x[0]['main'] if x else None)
df['weather_description'] = df['weather'].apply(lambda x: x[0]['description'] if x else None)
df['weather_icon'] = df['weather'].apply(lambda x: x[0]['icon'] if x else None)
# Drop the original 'weather' column
df = df.drop('weather', axis=1)
return df
def fetch_weather_for_cities(self, cities, start_date, end_date):
all_cities_weather_data = []
for city_name in cities:
lat_lon = self.get_lat_lon(city_name) # Call the method within the same class
if lat_lon:
lat, lon = lat_lon
df_weather = self.fetch_weather_data(lat, lon, start_date, end_date)
if not df_weather.empty:
df_weather['city'] = city_name # Add a column for the city name
all_cities_weather_data.append(df_weather)
else:
print(f"No weather data retrieved for {city_name}.")
else:
print(f"Failed to get latitude and longitude for {city_name}.")
if all_cities_weather_data:
all_data_df = pd.concat(all_cities_weather_data, ignore_index=True)
return all_data_df
else:
return pd.DataFrame()
def save_to_csv(self, df, file_name):
try:
df.to_csv(file_name, index=False)
print(f"Data successfully saved to {file_name}.")
except Exception as e:
print(f"Failed to save data to CSV. Error: {e}") |