<jupyter_start><jupyter_text>WeatherPy---- Written description of three observable trends based on the data.* Latitude and Temperature seem to have a strong correlation.* Correlation between latitude and the other factors is almost none.* Temperature rises the closest we get to the equator.<jupyter_code># Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import requests
import datetime
import scipy.stats as st
import json
from pprint import pprint

# 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).<jupyter_code>api_key = weather_api_key

url = "http://api.openweathermap.org/data/2.5/weather?"
units = "imperial"
query_url = f"{url}appid={api_key}&units={units}&q="

response = requests.get(query_url + city).json()
pprint(response)
latitude = []
longitude = []
temperature = []
humidity = []
cloudiness = []
wind_speed = []
city_name = []
country = []
date = []

sets = 1
counter = 1

print("Beginning Data Retrieval")
print("-----------------------------")

for city in cities:
    
    try:
        response = requests.get(query_url + city).json()
        latitude.append(response["coord"]["lat"])
        longitude.append(response["coord"]["lon"])
        temperature.append(response["main"]["temp"])
        humidity.append(response["main"]["humidity"])
        cloudiness.append(response["clouds"]["all"])
        wind_speed.append(response["wind"]["speed"])
        city_name.append(response["name"])
        country.append(response["sys"]["country"])
        date.append(response["dt"])
        city_record = response["name"]
        print(f"Processing Record {counter} of Set {sets} | {city_record}")
        
        counter += 1
        
        if counter == 51:
            counter = 0 
            sets += 1
                    
    except:
        print("City not found. Skipping...") 
    continue
    
print(f"-------------------------------")
print(f"Data Retrieval Complete")
print(f"-------------------------------")<jupyter_output>Beginning Data Retrieval
-----------------------------
Processing Record 1 of Set 1 | Albany
City not found. Skipping...
City not found. Skipping...
Processing Record 2 of Set 1 | Mataura
Processing Record 3 of Set 1 | Alofi
Processing Record 4 of Set 1 | Ushuaia
Processing Record 5 of Set 1 | Marsh Harbour
Processing Record 6 of Set 1 | Tuktoyaktuk
Processing Record 7 of Set 1 | Port Alfred
Processing Record 8 of Set 1 | Evensk
Processing Record 9 of Set 1 | Kaitangata
Processing Record 10 of Set 1 | Port Elizabeth
Processing Record 11 of Set 1 | Amuntai
Processing Record 12 of Set 1 | Yellowknife
Processing Record 13 of Set 1 | Kapaa
Processing Record 14 of Set 1 | Mongomo
Processing Record 15 of Set 1 | Vaini
Processing Record 16 of Set 1 | Beringovskiy
Processing Record 17 of Set 1 | Rawson
Processing Record 18 of Set 1 | George Town
City not found. Skipping...
Processing Record 19 of Set 1 | Chui
Processing Record 20 of Set 1 | Cape Town
Processing Record 21 of Set 1 | Aksu
Proces[...]<jupyter_text>Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame<jupyter_code>weather_df = pd.DataFrame({"City": city_name, "Lat": latitude, "Lng": longitude, "Temp": temperature, 
                           "Humidity": humidity, "Cloudiness": cloudiness, "Wind Speed": wind_speed, 
                           "Country": country, "Date": date})
weather_df.head()
weather_df.to_csv("./Resources/weather_df.csv")<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>weather_df.loc[weather_df['Humidity'] > 100] # There is not.<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>now = datetime.date.today()
month = now.month
day = now.day 
year = now.year


plt.figure()

plt.title(f"City Latitude vs. Temperature ({month}/{day}/{year})")
plt.xlabel("Latitude")
plt.ylabel("Temperature (F)")
plt.scatter(latitude, temperature, edgecolors="black", alpha=.75)
plt.grid(True)
plt.savefig("./Plots/Latitude_vs_Temperature.png")
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Humidity Plot<jupyter_code>plt.figure()

plt.title(f"City Latitude vs. Humidity ({month}/{day}/{year})")
plt.xlabel("Latitude")
plt.ylabel("Humidity (%)")
plt.scatter(latitude, humidity, edgecolors="black", alpha=.75)
plt.grid(True)
plt.savefig("./Plots/Latitude_vs_Humidity.png")
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Cloudiness Plot<jupyter_code>plt.figure()

plt.title(f"City Latitude vs. Cloudiness ({month}/{day}/{year})")
plt.xlabel("Latitude")
plt.ylabel("Cloudiness (%)")
plt.scatter(latitude, cloudiness, edgecolors="black", alpha=.75)
plt.grid(True)
plt.savefig("./Plots/Latitude_vs_Cloudiness.png")
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Wind Speed Plot<jupyter_code>plt.figure()

plt.title(f"City Latitude vs. Wind Speed ({month}/{day}/{year})")
plt.xlabel("Latitude")
plt.ylabel("Wind Speed (mph)")
plt.scatter(latitude, wind_speed, edgecolors="black", alpha=.75)
plt.grid(True)
plt.savefig("./Plots/Latitude_vs_WindSpeed.png")
plt.show()<jupyter_output><empty_output><jupyter_text>Linear Regression<jupyter_code># Separate Northern and Southern Hemispheres
Northern = weather_df.loc[weather_df['Lat'] >= 0]
Southern = weather_df.loc[weather_df['Lat'] < 0]<jupyter_output><empty_output><jupyter_text>Northern Hemisphere - Temp vs. Latitude Linear Regression<jupyter_code>plt.figure()

plt.xlabel("Latitude")
plt.ylabel("Temperature (F)")
plt.scatter(Northern['Temp'], Northern['Lat'])

correlation = st.pearsonr(Northern['Temp'], Northern['Lat'])

(slope, intercept, rvalue, pvalue, stderr) = st.linregress(Northern['Temp'], Northern['Lat'])
regress_values = Northern['Temp'] * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
plt.plot(Northern['Temp'],regress_values,"r-")
plt.annotate(line_eq,(-30,5),fontsize=15,color="red")

plt.savefig("./Plots/Temp_vs_Latitude_LR_NorthH.png")

plt.show()

print(f"The r-value is {round(correlation[0],2)}")<jupyter_output><empty_output><jupyter_text>Southern Hemisphere - Temp vs. Latitude Linear Regression<jupyter_code>plt.figure()

plt.xlabel("Latitude")
plt.ylabel("Temperature (F)")
plt.scatter(Southern['Temp'], Southern['Lat'])

correlation = st.pearsonr(Southern['Temp'], Southern['Lat'])

(slope, intercept, rvalue, pvalue, stderr) = st.linregress(Southern['Temp'], Southern['Lat'])
regress_values = Southern['Temp'] * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
plt.plot(Southern['Temp'],regress_values,"r-")
plt.annotate(line_eq,(70,-53),fontsize=15,color="red")

plt.savefig("./Plots/Temp_vs_Latitude_LRSouthH.png")

plt.show()

print(f"The r-value is {round(correlation[0],2)}")<jupyter_output><empty_output><jupyter_text>The analysis shows a strong negative correlation between temperature and latitude in the northern hemisphere and a Mild one in the southern hemisphere. This may sugest that in the northern hemisphere the temperatures are linked to the latitude but then again, correlation does not imply causation.   Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code>plt.figure()

plt.xlabel("Latitude")
plt.ylabel("Humidity (%)")
plt.scatter(Northern['Humidity'], Northern['Lat'])

correlation = st.pearsonr(Northern['Humidity'], Northern['Lat'])

(slope, intercept, rvalue, pvalue, stderr) = st.linregress(Northern['Humidity'], Northern['Lat'])
regress_values = Northern['Humidity'] * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
plt.plot(Northern['Humidity'],regress_values,"r-")
plt.annotate(line_eq,(7,71),fontsize=15,color="red")

plt.savefig("./Plots/Humidity_vs_Latitude_LR_NorthH.png")

plt.show()

print(f"The r-value is {round(correlation[0],2)}")<jupyter_output><empty_output><jupyter_text>Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code>plt.figure()

plt.xlabel("Latitude")
plt.ylabel("Humidity (%)")
plt.scatter(Southern['Humidity'], Southern['Lat'])

correlation = st.pearsonr(Southern['Humidity'], Southern['Lat'])

(slope, intercept, rvalue, pvalue, stderr) = st.linregress(Southern['Humidity'], Southern['Lat'])
regress_values = Southern['Humidity'] * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
plt.plot(Southern['Humidity'],regress_values,"r-")
plt.annotate(line_eq,(20,-5),fontsize=15,color="red")

plt.savefig("./Plots/Humidity_vs_Latitude_LR_SouthH.png")

plt.show()

print(f"The r-value is {round(correlation[0],2)}")<jupyter_output><empty_output><jupyter_text>The analysis shows a weak correlation between humidity and latitude in both northern and southern hemispheres. It may be that they are not related.    Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code>plt.figure()

plt.xlabel("Latitude")
plt.ylabel("Cloudiness (%)")
plt.scatter(Northern['Cloudiness'], Northern['Lat'])

correlation = st.pearsonr(Northern['Cloudiness'], Northern['Lat'])

(slope, intercept, rvalue, pvalue, stderr) = st.linregress(Northern['Cloudiness'], Northern['Lat'])
regress_values = Northern['Cloudiness'] * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
plt.plot(Northern['Cloudiness'],regress_values,"r-")
plt.annotate(line_eq,(20,75),fontsize=15,color="red")

plt.savefig("./Plots/Cloudiness_vs_Latitude_LR_NorthH.png")

plt.show()

print(f"The r-value is {round(correlation[0],2)}")<jupyter_output><empty_output><jupyter_text>Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code>plt.figure()

plt.xlabel("Latitude")
plt.ylabel("Cloudiness (%)")
plt.scatter(Southern['Cloudiness'], Southern['Lat'])

correlation = st.pearsonr(Southern['Cloudiness'], Southern['Lat'])

(slope, intercept, rvalue, pvalue, stderr) = st.linregress(Southern['Cloudiness'], Southern['Lat'])
regress_values = Southern['Cloudiness'] * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
plt.plot(Southern['Cloudiness'],regress_values,"r-")
plt.annotate(line_eq,(20,-50),fontsize=15,color="red")

plt.savefig("./Plots/Cloudiness_vs_Latitude_LR_SouthH.png")

plt.show()

print(f"The r-value is {round(correlation[0],2)}")<jupyter_output><empty_output><jupyter_text>The analysis shows a weak correlation between cloudiness and latitude in both northern and southern hemispheres. It may be that they are not related.    Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code>plt.figure()

plt.xlabel("Latitude")
plt.ylabel("Wind Speed (mph)")
plt.scatter(Northern['Wind Speed'], Northern['Lat'])

correlation = st.pearsonr(Northern['Wind Speed'], Northern['Lat'])

(slope, intercept, rvalue, pvalue, stderr) = st.linregress(Northern['Wind Speed'], Northern['Lat'])
regress_values = Northern['Wind Speed'] * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
plt.plot(Northern['Wind Speed'],regress_values,"r-")
plt.annotate(line_eq,(25,20),fontsize=15,color="red")

plt.savefig("./Plots/WindSpeed_vs_Latitude_LR_NorthH.png")

plt.show()

print(f"The r-value is {round(correlation[0],2)}")<jupyter_output><empty_output><jupyter_text>Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code>plt.figure()

plt.xlabel("Latitude")
plt.ylabel("Wind Speed (mph)")
plt.scatter(Southern['Wind Speed'], Southern['Lat'])

correlation = st.pearsonr(Southern['Wind Speed'], Southern['Lat'])

(slope, intercept, rvalue, pvalue, stderr) = st.linregress(Southern['Wind Speed'], Southern['Lat'])
regress_values = Southern['Wind Speed'] * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
plt.plot(Southern['Wind Speed'],regress_values,"r-")
plt.annotate(line_eq,(15,-54),fontsize=15,color="red")

plt.savefig("./Plots/WindSpeed_vs_Latitude_LR_SouthH.png")

plt.show()

print(f"The r-value is {round(correlation[0],2)}")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15590481132774853, 'fraction_numerical': 0.013566609830232041, 'mean_word_length': 5.590131900341964, 'pattern_counts': {'":': 9, '<': 73, '<?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': '647476', 'license': 'ADSL', 'n_tokens_mistral': 4894, 'n_tokens_neox': 4435, 'n_words': 1040, 'path': 'WeatherPy/WeatherPy.ipynb', 'repo_name': 'lamb-jack/python-api-challenge', 'size': '13489'}