<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 = []

# Create a set of random lat and lng combinations
lats = np.random.uniform(lat_range[0], lat_range[1], size=1500)
lngs = np.random.uniform(lng_range[0], lng_range[1], 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)

# Print the city count to confirm sufficient count
len(cities)<jupyter_output><empty_output><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).> **HINT:** The OpenWeatherMap API only allows 60 calls per minute under their free plan. Try using `time.sleep(60)` after each set of 50 cities to avoid API errors due to large calls.<jupyter_code># Create empty weather_json list to store returns

weather_json = []

# Loop through cities and build weather data dictionary from api response

for (n, city) in enumerate(cities, start=0):

    url = "http://api.openweathermap.org/data/2.5/weather?"
    query_url = url + "appid=" + weather_api_key + "&q=" + city + '&units=metric'

    try:
        response = requests.get(query_url).json()
        clouds = response['clouds']['all']
        country = response['sys']['country']    
        date = response['dt']
        humidity = response['main']['humidity']
        longitude = response['coord']['lon']
        latitude = response['coord']['lat']
        temp = response['main']['temp']
        wind_speed = response['wind']['speed']
        weather_data = {"City": city,
                        "Temperature": temp,
                        "Humidity": humidity,
                        "Cloudiness": clouds,
                        "Wind Speed": wind_speed,
                        "Country": country,
                        "Date": date,
                        "Longitude": longitude,
                        "Latitude": latitude}
        weather_json.append(weather_data)         
        # Print success message
        print(f'{n}: {city} loaded.')
    except:
        # Print failure message if city fails to load
        print(f'{n}: {city} failed to load.')<jupyter_output>0: mponela loaded.
1: srivardhan loaded.
2: kytmanovo loaded.
3: hofn loaded.
4: butaritari loaded.
5: khatanga loaded.
6: bafq loaded.
7: cabo san lucas loaded.
8: toftir failed to load.
9: ponta do sol loaded.
10: puerto ayora loaded.
11: katsuura loaded.
12: grand river south east failed to load.
13: kapaa loaded.
14: nyurba loaded.
15: nizhneyansk failed to load.
16: dhule loaded.
17: jamestown loaded.
18: souillac loaded.
19: hilo loaded.
20: praia da vitoria loaded.
21: bengkulu loaded.
22: punta arenas loaded.
23: taolanaro failed to load.
24: leningradskiy loaded.
25: busselton loaded.
26: atuona loaded.
27: bethel loaded.
28: narsaq loaded.
29: georgetown loaded.
30: vao loaded.
31: ribeira grande loaded.
32: albany loaded.
33: hermanus loaded.
34: castro loaded.
35: nanortalik loaded.
36: barentsburg failed to load.
37: lebu loaded.
38: maloshuyka failed to load.
39: cocal loaded.
40: belushya guba failed to load.
41: new norfolk loaded.
42: cidreira loaded.
43: amderma faile[...]<jupyter_text>Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame<jupyter_code>weather_df = pd.DataFrame(weather_json)
weather_df.to_csv("output_data/weather_df.csv", index=False, header=True)
weather_df<jupyter_output><empty_output><jupyter_text>Inspect the data and remove the cities where the humidity > 100%.----Skip this step if there are no cities that have humidity > 100%.<jupyter_code>#  Get the indices of cities that have humidity over 100%.
weather_df_clean = weather_df[weather_df['Humidity'] <= 100]
weather_df_clean
# Make a new DataFrame equal to the city data to drop all humidity outliers by index.
# Passing "inplace=False" will make a copy of the city_data DataFrame, which we call "clean_city_data".

# I handled this issue differently<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>lat_v_temp = plt.scatter(weather_df_clean['Latitude'], weather_df_clean['Temperature'])
plt.title("Latitude vs. Temperature")
plt.xlabel("Latitude")
plt.ylabel("Temperature (Celsius)")
plt.savefig("output_data/lat_v_temp.png")<jupyter_output><empty_output><jupyter_text>Latitude vs. Humidity Plot<jupyter_code>lat_v_humid = plt.scatter(weather_df_clean['Latitude'], weather_df_clean['Humidity'])
plt.title("Latitude vs. Humidity")
plt.xlabel("Latitude")
plt.ylabel("Humidity")
plt.savefig("output_data/lat_v_humid.png")<jupyter_output><empty_output><jupyter_text>Latitude vs. Cloudiness Plot<jupyter_code>lat_v_cloud = plt.scatter(weather_df_clean['Latitude'], weather_df_clean['Cloudiness'])
plt.title("Latitude vs. Cloudiness")
plt.xlabel("Latitude")
plt.ylabel("Cloudiness")
plt.savefig("output_data/lat_v_cloud.png")<jupyter_output><empty_output><jupyter_text>Latitude vs. Wind Speed Plot<jupyter_code>lat_v_wind = plt.scatter(weather_df_clean['Latitude'], weather_df_clean['Wind Speed'])
plt.title("Latitude vs. Wind Speed")
plt.xlabel("Latitude")
plt.ylabel("Wind Speed")
plt.savefig("output_data/lat_v_wind.png")<jupyter_output><empty_output><jupyter_text>Linear Regression<jupyter_code>northern_weather_df = weather_df_clean.loc[weather_df_clean["Latitude"] >= 0]
southern_weather_df = weather_df_clean.loc[weather_df_clean["Latitude"] < 0]<jupyter_output><empty_output><jupyter_text>Northern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code>x_values = northern_weather_df['Latitude']
y_values = northern_weather_df['Temperature']
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
regress_values = x_values * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
plt.scatter(x_values,y_values)
plt.plot(x_values,regress_values,"r-")
plt.title('Northern Hemisphere - Latitude vs. Temperature (C)')
plt.xlabel('Latitude')
plt.ylabel('Temperature (C)')
plt.show()
plt.savefig("output_data/nortnern-hemisphere-lat_v_temp.png")<jupyter_output><empty_output><jupyter_text>Southern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code>x_values = southern_weather_df['Latitude']
y_values = southern_weather_df['Temperature']
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
regress_values = x_values * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
plt.scatter(x_values,y_values)
plt.plot(x_values,regress_values,"r-")
plt.title('Souther Hemisphere - Latitude vs. Temperature (C)')
plt.xlabel('Latitude')
plt.ylabel('Temperature (C)')
plt.show()
plt.savefig("output_data/southern-hemisphere-lat_v_temp.png")<jupyter_output><empty_output><jupyter_text>Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code>x_values = northern_weather_df['Latitude']
y_values = northern_weather_df['Humidity']
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
regress_values = x_values * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
plt.scatter(x_values,y_values)
plt.plot(x_values,regress_values,"r-")
plt.title('Northern Hemisphere - Latitude vs. Humidity')
plt.xlabel('Latitude')
plt.ylabel('Humidity')
plt.show()
plt.savefig("output_data/nortnern-hemisphere-lat_v_humid.png")<jupyter_output><empty_output><jupyter_text>Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code>x_values = southern_weather_df['Latitude']
y_values = southern_weather_df['Humidity']
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
regress_values = x_values * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
plt.scatter(x_values,y_values)
plt.plot(x_values,regress_values,"r-")
plt.title('Southern Hemisphere - Latitude vs. Humidity')
plt.xlabel('Latitude')
plt.ylabel('Humidity')
plt.show()
plt.savefig("output_data/southern-hemisphere-lat_v_humid.png")<jupyter_output><empty_output><jupyter_text>Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code>x_values = northern_weather_df['Latitude']
y_values = northern_weather_df['Cloudiness']
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
regress_values = x_values * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
plt.scatter(x_values,y_values)
plt.plot(x_values,regress_values,"r-")
plt.title('Northern Hemisphere - Latitude vs. Cloudiness')
plt.xlabel('Latitude')
plt.ylabel('Cloudiness')
plt.show()
plt.savefig("output_data/nortnern-hemisphere-lat_v_cloud.png")<jupyter_output><empty_output><jupyter_text>Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code>x_values = southern_weather_df['Latitude']
y_values = southern_weather_df['Cloudiness']
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
regress_values = x_values * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
plt.scatter(x_values,y_values)
plt.plot(x_values,regress_values,"r-")
plt.title('Southern Hemisphere - Latitude vs. Cloudiness')
plt.xlabel('Latitude')
plt.ylabel('Cloudiness')
plt.show()
plt.savefig("output_data/southern-hemisphere-lat_v_cloud.png")<jupyter_output><empty_output><jupyter_text>Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code>x_values = northern_weather_df['Latitude']
y_values = northern_weather_df['wind_speed']
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
regress_values = x_values * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
plt.scatter(x_values,y_values)
plt.plot(x_values,regress_values,"r-")
plt.title('Northern Hemisphere - Latitude vs. Wind Speed')
plt.xlabel('Latitude')
plt.ylabel('Wind Speed')
plt.show()
plt.savefig("output_data/nortnern-hemisphere-lat_v_wind.png")<jupyter_output><empty_output><jupyter_text>Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code>x_values = southern_weather_df['Latitude']
y_values = southern_weather_df['wind_speed']
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
regress_values = x_values * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
plt.scatter(x_values,y_values)
plt.plot(x_values,regress_values,"r-")
plt.title('Southern Hemisphere - Latitude vs. Wind Speed')
plt.xlabel('Latitude')
plt.ylabel('Wind Speed')
plt.show()
plt.savefig("output_data/southern-hemisphere-lat_v_wind.png")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1239662447257384, 'fraction_numerical': 0.01189873417721519, 'mean_word_length': 5.635498320268757, 'pattern_counts': {'":': 9, '<': 74, '<?xml version=': 0, '>': 76, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '18', 'dir': 'jupyter-structured-clean-dedup', 'id': '334167', 'license': 'ADSL', 'n_tokens_mistral': 4374, 'n_tokens_neox': 4072, 'n_words': 949, 'path': 'WeatherPy.ipynb', 'repo_name': 'jtbuckwalter/UPBC-Assignment-06-Python-APIs', 'size': '11850'}