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