<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 pprint as pp
import datetime


# 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(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)

# 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.  Pull and store the following data:    - Temperature (F)    - Humidity (%)    - Cloudiness (%)    - Wind Speed (mph)- Include a print log of each city as it'sbeing processed (with the city number and city name).<jupyter_code># Create lists to store the requested data
tempF = []
maxTempF = []
humidity = []
cloudiness = []
windspeed = []
country = []
date = []
lat = []
lng = []
# Pull a sample of the weather response data for reference
sampleURL = "http://api.openweathermap.org/data/2.5/weather?appid=" + weather_api_key + "&units=imperial&q=london"
sampleResponse = requests.get(sampleURL)
sampleJSON = sampleResponse.json()
pp.pprint(sampleJSON)
testing = sampleJSON['coord']['lon']
testing
# Create the base URL
baseURL = "http://api.openweathermap.org/data/2.5/weather?appid="
cityNumber = 1
totalCities = len(cities)

# Loop to pull weather data on each city in the list
for city in cities:
    print(f"Pulling city #{cityNumber} of {totalCities}: {city}")
    try:
        query_url = baseURL + weather_api_key + "&units=imperial&q=" + city
        
        
        response = requests.get(query_url)
        responseJSON = response.json()
        tempF.append(responseJSON['main']['temp'])
        humidity.append(responseJSON['main']['humidity'])
        cloudiness.append(responseJSON['clouds']['all'])
        windspeed.append(responseJSON['wind']['speed'])
        country.append(responseJSON['sys']['country'])
        maxTempF.append(responseJSON['main']['temp_max'])
        date.append(responseJSON['dt'])
        lat.append(responseJSON['coord']['lat'])
        lng.append(responseJSON['coord']['lon'])        
    except:
        print("Bad Response")
    cityNumber += 1
# Zip up the lists
zippedList =  list(zip(cities, cloudiness, country, date, humidity, lat, lng, maxTempF, tempF, windspeed))
zippedList
# Create a dataframe from zipped list
weather_df = pd.DataFrame(zippedList, columns = ['City', 'Cloudiness', 'Country', 'Date', 'Humidity', 'Latitude', 'Longitude', 'MaxTemp', 'Temp', 'Windspeed']) 
weather_df<jupyter_output><empty_output><jupyter_text>Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame<jupyter_code>weather_df.to_csv("../output_data/weather_data.csv")
print("Export Complete")<jupyter_output>Export Complete<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>#Set the X and Y axis variables
x_axis = weather_df.Latitude
y_axis = weather_df.MaxTemp
# Set "now"
now = datetime.datetime.now()
# Plot
plt.scatter(x_axis, y_axis, marker='o')
plt.xlabel("Latitude")
plt.ylabel("Max Temperature (F)")
plt.title(f"City Latitude vs. Max Temperature ({now.month}/{now.day}/{now.year})")
plt.grid()
plt.show
plt.savefig('../output_data/fig1.png')<jupyter_output><empty_output><jupyter_text>Latitude vs. Humidity Plot<jupyter_code>#Set the X and Y axis variables
x_axis = weather_df.Latitude
y_axis = weather_df.Humidity
# Plot
plt.scatter(x_axis, y_axis, marker='o')
plt.xlabel("Latitude")
plt.ylabel("Humidity (%)")
plt.title(f"City Latitude vs. Humidity ({now.month}/{now.day}/{now.year})")
plt.grid()
plt.show
plt.savefig('../output_data/fig2.png')<jupyter_output><empty_output><jupyter_text>Latitude vs. Cloudiness Plot<jupyter_code>#Set the X and Y axis variables
x_axis = weather_df.Latitude
y_axis = weather_df.Cloudiness
# Plot
plt.scatter(x_axis, y_axis, marker='o')
plt.xlabel("Latitude")
plt.ylabel("Cloudiness (%)")
plt.title(f"City Latitude vs. Cloudiness ({now.month}/{now.day}/{now.year})")
plt.grid()
plt.show
plt.savefig('../output_data/fig3.png')<jupyter_output><empty_output><jupyter_text>Latitude vs. Wind Speed Plot<jupyter_code>#Set the X and Y axis variables
x_axis = weather_df.Latitude
y_axis = weather_df.Windspeed
# Plot
plt.scatter(x_axis, y_axis, marker='o')
plt.xlabel("Latitude")
plt.ylabel("Windspeed (mph)")
plt.title(f"City Latitude vs. Wind Speed ({now.month}/{now.day}/{now.year})")
plt.grid()
plt.show
plt.savefig('../output_data/fig4.png')<jupyter_output><empty_output><jupyter_text>Linear Regression<jupyter_code># Create Northern and Southern Hemisphere DataFrames
hemisphereNorth = weather_df[weather_df['Latitude'].astype(float)>0]
hemisphereSouth = weather_df[weather_df['Latitude'].astype(float)<0]<jupyter_output><empty_output><jupyter_text>Southern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code>#Set the X and Y axis variables
x_axis = hemisphereSouth.Latitude.astype(float)
y_axis = hemisphereSouth.MaxTemp.astype(float)

# Plot
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_axis, y_axis)
regress_values = x_axis * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))

plt.scatter(x_axis, y_axis)
plt.plot(x_axis,regress_values,"r-")
plt.xlabel("Latitude")
plt.ylabel("Max Temperature (F)")
plt.title(f"City Latitude vs. Max Temperature for Cities in the Southern Hemisphere ({now.month}/{now.day}/{now.year})")
plt.annotate(line_eq,(-55,80),fontsize=15,color="red")
plt.show
print(f"The r-squared value is: {rvalue}")
plt.savefig('../output_data/fig5.png')<jupyter_output>The r-squared value is: 0.6084585635327757<jupyter_text>Northern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code>#Set the X and Y axis variables
x_axis = hemisphereNorth.Latitude.astype(float)
y_axis = hemisphereNorth.MaxTemp.astype(float)

# Plot
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_axis, y_axis)
regress_values = x_axis * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))

plt.scatter(x_axis, y_axis)
plt.plot(x_axis,regress_values,"r-")
plt.xlabel("Latitude")
plt.ylabel("Max Temperature (F)")
plt.title(f"City Latitude vs. Max Temperature for Cities in the Northern Hemisphere ({now.month}/{now.day}/{now.year})")
plt.annotate(line_eq,(0,30),fontsize=15,color="red")
plt.show
print(f"The r-squared value is: {rvalue}")
plt.savefig('../output_data/fig6.png')<jupyter_output>The r-squared value is: -0.8464918182571072<jupyter_text>Observations:- Regression shows that there is a weak correlation between latitude and max temperature in the southern hemisphere- Regression shows that there is a strong negative correlation between latitude and max temperature in the northern hemisphere   Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code>#Set the X and Y axis variables
x_axis = hemisphereSouth.Latitude.astype(float)
y_axis = hemisphereSouth.Humidity.astype(float)

# Plot
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_axis, y_axis)
regress_values = x_axis * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))

plt.scatter(x_axis, y_axis)
plt.plot(x_axis,regress_values,"r-")
plt.xlabel("Latitude")
plt.ylabel("Humidity (%)")
plt.title(f"City Latitude vs. Humidity for Cities in the Southern Hemisphere ({now.month}/{now.day}/{now.year})")
plt.annotate(line_eq,(-57,20),fontsize=15,color="red")
plt.show
print(f"The r-squared value is: {rvalue}")
plt.savefig('../output_data/fig7.png')<jupyter_output>The r-squared value is: 0.20249681003082784<jupyter_text>Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code>#Set the X and Y axis variables
x_axis = hemisphereNorth.Latitude.astype(float)
y_axis = hemisphereNorth.Humidity.astype(float)

# Plot
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_axis, y_axis)
regress_values = x_axis * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))

plt.scatter(x_axis, y_axis)
plt.plot(x_axis,regress_values,"r-")
plt.xlabel("Latitude")
plt.ylabel("Humidity (%)")
plt.title(f"City Latitude vs. Humidity for Cities in the Northern Hemisphere ({now.month}/{now.day}/{now.year})")
plt.annotate(line_eq,(45,20),fontsize=15,color="red")
plt.show
print(f"The r-squared value is: {rvalue}")
plt.savefig('../output_data/fig8.png')<jupyter_output>The r-squared value is: 0.05980660015706249<jupyter_text>Observations:- Regressions shows that there is no correlation between latitude and humidity in either hemisphere   Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code>#Set the X and Y axis variables
x_axis = hemisphereSouth.Latitude.astype(float)
y_axis = hemisphereSouth.Cloudiness.astype(float)

# Plot
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_axis, y_axis)
regress_values = x_axis * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))

plt.scatter(x_axis, y_axis)
plt.plot(x_axis,regress_values,"r-")
plt.xlabel("Latitude")
plt.ylabel("Cloudiness (%)")
plt.title(f"City Latitude vs. Cloudiness for Cities in the Southern Hemisphere ({now.month}/{now.day}/{now.year})")
plt.annotate(line_eq,(-57,20),fontsize=15,color="red")
plt.show
print(f"The r-squared value is: {rvalue}")
plt.savefig('../output_data/fig9.png')<jupyter_output>The r-squared value is: 0.024292682801840885<jupyter_text>Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code>#Set the X and Y axis variables
x_axis = hemisphereNorth.Latitude.astype(float)
y_axis = hemisphereNorth.Humidity.astype(float)

# Plot
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_axis, y_axis)
regress_values = x_axis * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))

plt.scatter(x_axis, y_axis)
plt.plot(x_axis,regress_values,"r-")
plt.xlabel("Latitude")
plt.ylabel("Humidity (%)")
plt.title(f"City Latitude vs. Humidity for Cities in the Northern Hemisphere ({now.month}/{now.day}/{now.year})")
plt.annotate(line_eq,(45,20),fontsize=15,color="red")
plt.show
print(f"The r-squared value is: {rvalue}")
plt.savefig('../output_data/fig10.png')<jupyter_output>The r-squared value is: 0.05980660015706249<jupyter_text>Observations:- Regression shows that there is no correlation between latitude and humidity in either hemisphere   Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code>#Set the X and Y axis variables
x_axis = hemisphereNorth.Latitude.astype(float)
y_axis = hemisphereNorth.Windspeed.astype(float)

# Plot
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_axis, y_axis)
regress_values = x_axis * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))

plt.scatter(x_axis, y_axis)
plt.plot(x_axis,regress_values,"r-")
plt.xlabel("Latitude")
plt.ylabel("Windspeed (mph)")
plt.title(f"City Latitude vs. Windspeed for Cities in the Northern Hemisphere ({now.month}/{now.day}/{now.year})")
plt.annotate(line_eq,(0,27),fontsize=15,color="red")
plt.show
print(f"The r-squared value is: {rvalue}")
plt.savefig('../output_data/fig11.png')<jupyter_output>The r-squared value is: 0.08123458839697116<jupyter_text>Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code>#Set the X and Y axis variables
x_axis = hemisphereSouth.Latitude.astype(float)
y_axis = hemisphereSouth.Windspeed.astype(float)

# Plot
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_axis, y_axis)
regress_values = x_axis * slope + intercept
line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))

plt.scatter(x_axis, y_axis)
plt.plot(x_axis,regress_values,"r-")
plt.xlabel("Latitude")
plt.ylabel("Windspeed (mph)")
plt.title(f"City Latitude vs. Windspeed for Cities in the Southern Hemisphere ({now.month}/{now.day}/{now.year})")
plt.annotate(line_eq,(-40,25),fontsize=15,color="red")
plt.show
print(f"The r-squared value is: {rvalue}")
plt.savefig('../output_data/fig12.png')<jupyter_output>The r-squared value is: -0.35125505629648335
{'fraction_non_alphanumeric': 0.13894324853228962, 'fraction_numerical': 0.020322143609814842, 'mean_word_length': 5.891597510373444, 'pattern_counts': {'":': 0, '<': 61, '<?xml version=': 0, '>': 61, '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': '17', 'dir': 'jupyter-structured-clean-dedup', 'id': '451537', 'license': 'ADSL', 'n_tokens_mistral': 5091, 'n_tokens_neox': 4648, 'n_words': 1081, 'path': 'WeatherPy/WeatherPy.ipynb', 'repo_name': '00geist00/python-api-challenge', 'size': '13286'}