<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. Observations:1. As you get closer to the equator (latitude = 0) the maximum temperture increases.2. In the Northern hempisphere, as latitude increases the maximum temperature decreases. This is because the further North you go the lower the temperatures get.3. the further north you go in the southern hempisphere (closer to equator) the higher the maximum temperature gets.<jupyter_code># Dependencies and Setup
#!pip install citipy
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import requests
import time
from scipy.stats import linregress
import csv
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
print(len(cities))<jupyter_output>623<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 empty lists to store data on random cities
city_data = []
cloudiness = []
country = []
date = []
humidity = []
lat = []
lng = []
max_temp = []
wind_speed = []

url = "http://api.openweathermap.org/data/2.5/weather?"
units = "imperial"

count = 1
set_count = 1
print("Beginning Data Retrieval")
print("-------------------------")
for city in cities: 
    query_url = f"{url}appid={weather_api_key}&q={city}&units={units}"
    response = requests.get(query_url).json()
    try:   
        city_name = response['name']
        print(f"Processing Record {count} of Set {set_count} | {city_name}")
        #Fill empty lists
        city_data.append(response['name'])
        cloudiness.append(response['clouds']['all'])
        country.append(response['sys']['country'])
        date.append(response['dt'])
        humidity.append(response['main']['humidity'])
        lat.append(response['coord']['lat'])
        lng.append(response['coord']['lon'])
        max_temp.append(response['main']['temp_max'])
        wind_speed.append(response['wind']['speed'])
        #add 1 to city count after each loop
        count +=1
        if count == 50:
            count = 0
            set_count +=1
    except KeyError: 
        print("City not found. Skipping...")<jupyter_output>Beginning Data Retrieval
-------------------------
Processing Record 1 of Set 1 | Yellowknife
Processing Record 2 of Set 1 | Aswān
Processing Record 3 of Set 1 | Upernavik
Processing Record 4 of Set 1 | Varca
Processing Record 5 of Set 1 | Antonina
Processing Record 6 of Set 1 | <NAME>
Processing Record 7 of Set 1 | Kapaa
Processing Record 8 of Set 1 | Yining
Processing Record 9 of Set 1 | Carnarvon
Processing Record 10 of Set 1 | Rikitea
Processing Record 11 of Set 1 | Clyde River
Processing Record 12 of Set 1 | Provideniya
Processing Record 13 of Set 1 | La Ronge
Processing Record 14 of Set 1 | Mehamn
Processing Record 15 of Set 1 | Cherskiy
Processing Record 16 of Set 1 | Bonfim
Processing Record 17 of Set 1 | Saint Paul Harbor
City not found. Skipping...
Processing Record 18 of Set 1 | Busselton
Processing Record 19 of Set 1 | Sitka
Processing Record 20 of Set 1 | Albany
Processing Record 21 of Set 1 | Zhigansk
Processing Record 22 of Set 1 | Nago
Processing Record 23 of Set 1[...]<jupyter_text>Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame<jupyter_code>#Create dataframe 
city_df = pd.DataFrame({"City": city_data,"Cloudiness": cloudiness, "Country": country, "Date": date,
                        "Humidity": humidity, "Lat": lat, "Long": lng, "Max temp": max_temp,
                       "Wind Speed": wind_speed})
#Convert python date to readable date
current_date = str(city_df.iloc[0,3])
current_date = datetime.datetime.fromtimestamp(int(current_date)).strftime('%m-%d-%Y')
#Export data to a csv
city_df.to_csv('city_data.csv', index=False)
city_df.head()<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>plt.scatter(city_df["Lat"], city_df["Max temp"],marker = 'o',facecolors = 'blue',edgecolors = 'black')
plt.xlabel("Latitude")
plt.ylabel("Max Temperature (F)")
plt.title("City Latitude vs. Max Temperature" + " " + current_date)
plt.grid()
plt.savefig("City Latitude vs. Max Temperature.png")<jupyter_output><empty_output><jupyter_text>The plot is showing latitude of cities vs their maximum temperature. The closer latitude is to zero and 20, the higher the max temperature is. Which means the closer we get to the equator the higher the max temp is.   Latitude vs. Humidity Plot<jupyter_code>plt.scatter(city_df["Lat"], city_df["Humidity"],marker = 'o',facecolors = 'blue',edgecolors = 'black')
plt.xlabel("Latitude")
plt.ylabel("Humidity %")
plt.title("City Latitude vs. Humidity" + " " + current_date)
plt.grid()
plt.savefig("City Latitude vs. Humidity.png")<jupyter_output><empty_output><jupyter_text>This plot compares the humidity to latitde. There seems to be no correlation between humidity and latitude.   Latitude vs. Cloudiness Plot<jupyter_code>plt.scatter(city_df["Lat"], city_df["Cloudiness"],marker = 'o',facecolors = 'blue',edgecolors = 'black')
plt.xlabel("Latitude")
plt.ylabel("Cloudiness %")
plt.title("City Latitude vs. Cloudiness" + " " + current_date)
plt.grid()
plt.savefig("City Latitude vs. Cloudiness.png")<jupyter_output><empty_output><jupyter_text>This plot shows the cloudiness percent vs. the city latitude. There does not appear to be a correlation between the two.  Latitude vs. Wind Speed Plot<jupyter_code>plt.scatter(city_df["Lat"], city_df["Wind Speed"],marker = 'o',facecolors = 'blue',edgecolors = 'black')
plt.xlabel("Latitude")
plt.ylabel("Wind Speed (mph)")
plt.title("City Latitude vs. Wind Speed" + " " + current_date)
plt.grid()
plt.savefig("City Latitude vs. Wind Speed.png")
This plot shows wind speed vs. latitude.<jupyter_output><empty_output><jupyter_text>Linear Regression<jupyter_code># OPTIONAL: Create a function to create Linear Regression plots
#The function takes xvalues,yvalues, and xy location of the regression annotation as parameters
def linear_regress(x_val,y_val,x_loc,y_loc):
    (slope, intercept, r_val, _, _) = linregress(x_val, y_val)
    regress_val = x_val*slope + intercept
    line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
    plt.plot(x_val,regress_val,"r-")
    plt.annotate(line_eq,(x_loc,y_loc), fontsize=15,color="red")
    return print(f"The r-squared is {r_val}"), print(f"Regress eq: {line_eq}")
    
# Create Northern and Southern Hemisphere DataFrames
north_df = city_df.loc[city_df["Lat"]>=0,:]
south_df = city_df.loc[city_df["Lat"]<0,:]
south_df.head()<jupyter_output><empty_output><jupyter_text>Northern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code>plt.scatter(north_df["Lat"], north_df["Max temp"],marker = 'o',facecolors = 'blue',edgecolors = 'black')
plt.xlabel("Latitude")
plt.ylabel("Max Temperature (F)")
plt.title("Northern Hem. City Latitude vs. Max Temp" + " " + current_date)
linear_regress(north_df["Lat"],north_df["Max temp"],5,40)<jupyter_output>The r-squared is -0.7672218781774355
Regress eq: y = -0.61x + 92.75<jupyter_text>This plot shows that as latitude increases, the maximum temperature decreases. This is because the further North you gothe lower the temperatures get.   Southern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code>plt.scatter(south_df["Lat"], south_df["Max temp"],marker = 'o',facecolors = 'blue',edgecolors = 'black')
plt.xlabel("Latitude")
plt.ylabel("Max Temperature (F)")
plt.title("Southern Hem. City Latitude vs. Max Temp" + " " + current_date)
linear_regress(south_df["Lat"],south_df["Max temp"],-50,80)<jupyter_output>The r-squared is 0.8067114950319232
Regress eq: y = 0.76x + 82.33<jupyter_text>This plot shows the further north you go in the souther hempisphere (closer to equator) the higher the maximum temperaturegets.    Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code>plt.scatter(north_df["Lat"], north_df["Humidity"],marker = 'o',facecolors = 'blue',edgecolors = 'black')
plt.xlabel("Latitude")
plt.ylabel("Humidity %")
plt.title("Northern Hem. City Latitude vs. Humidity" + " " + current_date)
linear_regress(north_df["Lat"],north_df["Humidity"],50,10)<jupyter_output>The r-squared is -0.001500505047215615
Regress eq: y = -0.0x + 65.3<jupyter_text>This plot compares latitude and humidity % in the Northern hempisphere and there does not appear to be any correlation betweenthe two.    Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code>plt.scatter(south_df["Lat"],south_df["Humidity"],marker = 'o',facecolors = 'blue',edgecolors = 'black')
plt.xlabel("Latitude")
plt.ylabel("Humidity %")
plt.title("Southern Hem. City Latitude vs. Humidity" + " " + current_date)
linear_regress(south_df["Lat"],south_df["Humidity"],-50,20)<jupyter_output>The r-squared is -0.023842475556070233
Regress eq: y = -0.03x + 69.44<jupyter_text>This plot compares latitude and humidity % in the Southern hempisphere and there does not appear to be any correlation betweenthe two.    Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code>plt.scatter(north_df["Lat"], north_df["Cloudiness"],marker = 'o',facecolors = 'blue',edgecolors = 'black')
plt.xlabel("Latitude")
plt.ylabel("Cloudiness %")
plt.title("Northern Hem. City Latitude vs. Cloudiness" + " " + current_date)
linear_regress(north_df["Lat"],north_df["Cloudiness"],20,60)<jupyter_output>The r-squared is 0.030997474392436178
Regress eq: y = 0.06x + 52.25<jupyter_text>This plot compares latitude and cloudiness % in the Northern hempisphere and there does not appear to be any correlation between the two.    Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code>plt.scatter(south_df["Lat"], south_df["Cloudiness"],marker = 'o',facecolors = 'blue',edgecolors = 'black')
plt.xlabel("Latitude")
plt.ylabel("Cloudiness %")
plt.title("Southern Hem. City Latitude vs. Cloudiness" + " " + current_date)
linear_regress(south_df["Lat"],south_df["Cloudiness"],-50,55)<jupyter_output>The r-squared is -0.03802496394183691
Regress eq: y = -0.1x + 44.71<jupyter_text>This plot compares latitude and cloudiness % in the Southern hempisphere and there does not appear to be any correlation between the two.    Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code>plt.scatter(north_df["Lat"], north_df["Wind Speed"],marker = 'o',facecolors = 'blue',edgecolors = 'black')
plt.xlabel("Latitude")
plt.ylabel("Wind Speed (mph)")
plt.title("Northern Hem. City Latitude vs. Wind Speed" + " " + current_date)
linear_regress(north_df["Lat"],north_df["Wind Speed"],30,30)<jupyter_output>The r-squared is 0.04466887334357438
Regress eq: y = 0.01x + 7.73<jupyter_text>This plot compares latitude and wind speed in the Northern hempisphere and there does not appear to be any correlation between the two.    Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code>plt.scatter(south_df["Lat"], south_df["Wind Speed"],marker = 'o',facecolors = 'blue',edgecolors = 'black')
plt.xlabel("Latitude")
plt.ylabel("Wind Speed (mph)")
plt.title("Southern Hem. City Latitude vs. Wind Speed" + " " + current_date)
linear_regress(south_df["Lat"],south_df["Wind Speed"],-50,23)<jupyter_output>The r-squared is -0.05737892707841914
Regress eq: y = -0.02x + 8.17
{'fraction_non_alphanumeric': 0.12331268858186438, 'fraction_numerical': 0.028267428934413214, 'mean_word_length': 5.1469009272816, 'pattern_counts': {'":': 9, '<': 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': '585759', 'license': 'ADSL', 'n_tokens_mistral': 4480, 'n_tokens_neox': 4003, 'n_words': 1220, 'path': 'WeatherPy/WeatherScript.ipynb', 'repo_name': 'arimont123/python-api-challenge', 'size': '12599'}