<jupyter_start><jupyter_text>WeatherPy---- Note* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.<jupyter_code># Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import requests
import time
from scipy.stats import linregress

# Import API key
from api_keys import weather_api_key

# Incorporated citipy to determine city based on latitude and longitude
from citipy import citipy

# Output File (CSV)
output_data_file = "../output_data/cities.csv"

# Range of latitudes and longitudes
lat_range = (-90, 90)
lng_range = (-180, 180)<jupyter_output><empty_output><jupyter_text>Generate Cities List<jupyter_code># List for holding lat_lngs and cities
lat_lngs = []
cities = []
lat_lng_list = []

# Create a set of random lat and lng combinations
lats = np.random.uniform(low=-90.000, high=90.000, size=1500)
lngs = np.random.uniform(low=-180.000, high=180.000, size=1500)
lat_lngs = zip(lats, lngs)

# Identify nearest city for each lat, lng combination
for lat_lng in lat_lngs:
    city = citipy.nearest_city(lat_lng[0], lat_lng[1]).city_name
    
    # If the city is unique, then add it to a our cities list
    if city not in cities:
        cities.append(city)
        lat_lng_list.append(lat_lng)

# Print the city count to confirm sufficient count
len(cities)
print(cities)<jupyter_output>['sitka', 'tanshui', 'sao joao da barra', 'stoyba', 'gizo', 'taolanaro', 'vila franca do campo', 'butaritari', 'piacabucu', 'atuona', 'crib point', 'lincoln', 'tasiilaq', 'dingle', 'qaanaaq', 'punta arenas', 'clyde river', 'moindou', 'cherskiy', 'souillac', 'barrow', 'sao filipe', 'ribeira grande', 'tuktoyaktuk', 'beringovskiy', 'miles city', 'hermanus', 'barentsburg', 'albany', 'cape town', 'lebu', 'bluff', 'nikolskoye', 'pathein', 'vaini', 'murray bridge', 'luzilandia', 'luganville', 'cayenne', 'sayyan', 'port alfred', 'padang', 'ilulissat', 'busselton', 'rikitea', 'glen ellyn', 'kindu', 'kroya', 'vao', 'anapskaya', 'saskylakh', 'ushuaia', 'hanzhong', 'kavieng', 'amderma', 'quatre cocos', 'belushya guba', 'mataura', 'thompson', 'lawigan', 'ragandang', 'ende', 'kutum', 'pangnirtung', 'rumonge', 'codrington', 'grafton', 'sinnamary', 'kapaa', 'red wing', 'victoria', 'ambon', 'castro', 'albury', 'praia', 'puerto ayora', 'dikson', 'ancud', 'yurginskoye', 'talnakh', 'verkhovazhye', 'illoqq[...]<jupyter_text>Perform API Calls* Perform a weather check on each city using a series of successive API calls.* Include a print log of each city as it'sbeing processed (with the city number and city name).<jupyter_code>#Create dataframe with list of cities
city_df = pd.DataFrame(cities)
city_df = city_df.rename(columns={0: 'city'})

#Add lat and lngs to dataframe, create separate columns for lats and longs
city_df['lat_lngs'] = lat_lng_list
city_df['lat'] = city_df.lat_lngs.map(lambda x: str(x[0]))
city_df['long'] = city_df.lat_lngs.map(lambda x: str(x[1]))

city_df.head()
#Create new columns for data we'll be collecting from the API
city_df['temp'] = ""
city_df['max_temp'] = ""
city_df['humidity'] = ""
city_df['wind_speed'] = ""
city_df['clouds'] = ""

#Iterate over each row
for index, row in city_df.iterrows():
    city = row['city']
    print(f"Processing Record {index + 1} | {city}")
    city = city.replace(" ", "&")
    url = "http://api.openweathermap.org/data/2.5/weather?units=Imperial&q=" + city + "&APPID=" + weather_api_key
    print(url)
    weather = requests.get(url).json()
    try:
        city_df.loc[index, 'temp'] = weather['main']['temp']
        city_df.loc[index, 'max_temp'] = weather['main']['temp_max']
        city_df.loc[index, 'humidity'] = weather['main']['humidity']
        city_df.loc[index, 'wind_speed'] = weather['wind']['speed']
        city_df.loc[index, 'clouds'] = weather['clouds']['all']
    except:
        city_df.loc[index, 'temp'] = 'city not found'
        city_df.loc[index, 'humidity'] = 'city not found'
        city_df.loc[index, 'wind_speed'] = 'city not found'
        city_df.loc[index, 'clouds'] = 'city not found'
    time.sleep(.50)
    
print("----------------------")
print("Data Retrieval Complete")
print("-----------------------")
#Remove any cities that could not be found from the dataframe
city_df = city_df[city_df.temp != 'city not found']

#Check that there are still 500+ records
len(city_df)
#Convert lat from string to float object
city_df.lat = city_df.lat.astype(float)
city_df.head()<jupyter_output><empty_output><jupyter_text>Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame<jupyter_code>city_df.to_csv(output_data_file, encoding="utf-8", index=False)<jupyter_output><empty_output><jupyter_text>Plotting the Data* Use proper labeling of the plots using plot titles (including date of analysis) and axes labels.* Save the plotted figures as .pngs.  Latitude vs. Temperature Plot<jupyter_code>#Pull in today's date for graphs
import datetime
date = datetime.date.today()
date = time.strftime("%m/%d/%Y")

import seaborn as sns
sns.set()
plt.figure(figsize=(10,8))
plt.scatter(city_df['lat'], city_df['temp'])
plt.title(f"City Latitude vs. Temperature {date}", fontsize="18")
plt.xlabel("Latitude", fontsize="14")
plt.ylabel("Temperature (F)", fontsize="14")
plt.ylim(0, 120)

plt.savefig("Temperature.png")

plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Humidity Plot<jupyter_code>plt.figure(figsize=(10,8))
plt.scatter(city_df['lat'], city_df['humidity'])                              
plt.title(f"City Latitude vs. Humidity {date}", fontsize="18")
plt.xlabel("Latitude", fontsize="14")
plt.ylabel("Humidity (%)", fontsize="14")

plt.ylim(0,120)

plt.savefig("../Images/Humidity.png")

plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Cloudiness Plot<jupyter_code>plt.figure(figsize=(10,8))
plt.scatter(city_df['lat'], city_df['clouds'])                              
plt.title(f"City Latitude vs.Cloudiness {date}", fontsize="18")
plt.xlabel("Latitude", fontsize="14")
plt.ylabel("Wind Speed (mph)", fontsize="14")
plt.ylim(-20, 120)

plt.savefig("Cloudiness.png")

plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Wind Speed Plot<jupyter_code>plt.figure(figsize=(10,8))
plt.scatter(city_df['lat'], city_df['wind_speed'])                              
plt.title(f"City Latitude vs. Wind Speed {date}", fontsize="18")
plt.xlabel("Latitude", fontsize="14")
plt.ylabel("Wind Speed (mph)", fontsize="14")

plt.ylim(-5,45)

plt.savefig("Wind_Speed.png")

plt.show()
# Observable trends:

# From this dataset you can see that as we might expect, the temperature is higher at Latitude 0 (Equator) today and descreases as the latitude moves further from the Equator.
# You can also see that cloudiness and humidity don't seem to be dependent on latitude, but is fairly evenly disbursed.
# Finally, wind speed also doesn't seem to be related to latitude as windspeed for this dataset is clustered around 0.<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup