<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[-90.000], lat_range[90.000], size=1500)
lngs = np.random.uniform(lng_range[-180.000], lng_range[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.* Include a print log of each city as it'sbeing processed (with the city number and city name).<jupyter_code># Creating empty lists for each of the columns we need in the dataframe
city_name=[]
country=[]
date=[]
longitude=[]
latitude=[]
max_temp = []
humidity=[]
cloudiness=[]
wind_speed=[]
# Requesting data for each of the cities in the list by looping through
for city in cities:
    # setting the base URL
    url = "http://api.openweathermap.org/data/2.5/weather?"
    # setting the temperature unit of measurement
    units = "Fahrenheit"
    # building query URL to return our results in our desired unit of measurement (Fahrenheit)
    query_url = f"{url}appid={api_key}&q={city}&units={units}"
    weather_json = requests.get(query_url).json()
    try:
        city_name.append(weather_json["name"])
        country.append(weather_json["sys"]["country"])
        date.append(weather_json["dt"])
        longitude.append(weather_json["coord"]["lon"])
        latitude.append(weather_json["coord"]["lat"])
        max_temp.append(weather_json["main"]["temp_max"])
        humidity.append(weather_json["main"]["humidity"])
        cloudiness.append(weather_json["clouds"]["all"])
        wind_speed.append(weather_json["wind"]["speed"])
        print(f"{city} is found")
    except:
        print("City not found")
# Creating a dictionary of lists of the data pulled from our query
weather_dictionary = {
    "City Name": city_name,
    "Country": country,
    "Date": date,
    "Longitude": longitude,
    "Latitude": latitude,
    "Max Temperature": max_temp,
    "Humidity": humidity,
    "Cloudiness": cloudiness,
    "Wind Speed (mph)": wind_speed 
}
weather_data_df = pd.DataFrame(weather_dict)<jupyter_output><empty_output><jupyter_text>Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame<jupyter_code># Exporting file as a csv including the header, but not the index
weather_data_df.to_csv("../Output/weather_data.csv", index=False, header=True)
weather_data_df.head()
# generating a table of  summary statistics on the weather data
weather_data_df.describe()<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_data_df.loc[weather_data_df["Humidity"] >= 100]["Humidity"].count()
# 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".
clean_city_data = weather_data_df
for {city} in weather_data_df:
    clean_city_data = weather_data_df.drop({city})
clean_city_data
# Exporting cleaned data to a news csv
clean_city_data_df.to_csv("../Output/clean_city_data.csv", index=False, header=True)
clean_city_data_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># setting x and y values
x_values = latitude
y_values = max_temp

# generating the plot, setting and and y labels, setting title, saving image
plt.scatter(x_values,y_values, marker = "o", facecolor = "blue", edgecolor="black")

plt.xlabel('Latitude')
plt.ylabel('Max Temprature (F)')
plt.title("City Latitude vs. Max Temperature (%s)" % time.strftime("%x"))
plt.grid()
plt.savefig("../Images/city_lat_vs_temp.png")
plt.show()
# writing a couple of lines about the plot
print("As a city's latitude approaches 0, the temperature increases. The further a city's latitude is from 0 degrees (the equator) the lower the maximum temperature is. There is a strong correlation between a city's latitude and its maximum tmeperature.")<jupyter_output><empty_output><jupyter_text>Latitude vs. Humidity Plot<jupyter_code># setting x and y values
x_values = latitude
y_values = humidity

# generating  the plot, setting x and y labels, saving image
plt.scatter(x_values, y_values, marker = "o", facecolor = "blue", edgecolor = "black")

plt.xlabel(Latitude)
plt.ylabel(Humidity)
plt.title("City Latitude vs. Humidity")
plt.grid()
plt.savefig("../Images/city_latitude_vs_humidity.png")
plt.show()
# printing a statement about latitude vs humidity
print("While there are clusters of individual plot marks, there does not appear to be a strong correlation between a city's latitude and the level of humidity in the city.")<jupyter_output><empty_output><jupyter_text>Latitude vs. Cloudiness Plot<jupyter_code># setting x and y values
x_values = latitude
y_values = cloudiness

# generating the plot, setting x and y labels, setting color, saving the plot as an image file

plt. scatter(x_values, y_values, marker = "o", facecolor = "blue", edgecolor = "black")

plt.xlabel("Latitude")
plt.ylabel("Cloudiness (%)")
plt.title(City Latitude vs Cloudiness)
plt.grid()
plt.savefig("../Images/city_latitude_vs_cloudiness.png")
plt.show()
# Writing a statement about the plot
print("There is no relationship between a city's latitude and the percent cloudiness.")<jupyter_output><empty_output><jupyter_text>Latitude vs. Wind Speed Plot<jupyter_code># Setting x and y values
x_values = latitude
y_values = wind_speed

# generating the plot

plt.scatter(x_values, y_values, marker = "o", facecolor = "blue", edgecolor = "black")

plt.xlabel("Latitude")
plt.ylabel("Wind Speed (mph)")
plt.title("Latitude  vs. Wind Speed")
plt.grid()
plt.savefig("../Images/latitude_vs_wind_speed.png")
plt.show()
# Printing a statement about the plot
print("The plot shows that a city's longitude does not impact the windspeed in the city. Most city's on the plot experience a small amount of wind (between 5-10 mph) with a few outliers.")<jupyter_output><empty_output><jupyter_text>Linear Regression<jupyter_code># Generating new dataframes to perform the linear regression on

n_hem_df = clean_city_data.loc[clean_city_data["Lat"] >= 0]
s_hem_df = clean_city_data.loc[clean_city_data["Lat"] < 0]<jupyter_output><empty_output><jupyter_text>Northern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code># Setting the x and y values
x_values = pd.to_numeric(n_hem['Latitude']).astype(float)
y_values = pd.to_numeric(n_hem['Maximum Temperature']).astype(float)
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
regress_values = x_values * slope + intercept
line_equation = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
# Printing a statement about what we did
print("To perform the linear regression, I set the x and y values. The slope (rounded to 2 decimals) multipled by the x values plus the intercept gives you the relationship that the y value has to the x values. In this case, the maximum temperature has a slight relationship to the city's latitude, but it is not strongly correlated.")<jupyter_output><empty_output><jupyter_text>Southern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code>x_values = pd.to_numeric(s_hem['Latitude']).astype(float)
y_values = pd.to_numeric(s_hem['Maximum Temperature']).astype(float)
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
regress_values = x_values * slope + intercept
line_equation = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
# Printing a statement about what we did
print("To perform the linear regression, I set the x and y values. The slope (rounded to 2 decimals) multipled by the x values plus the intercept gives you the relationship that the y value has to the x values. In this case, the maximum temperature has a slight to moderate relationship to the city's latitude, but it is not strongly correlated.")<jupyter_output><empty_output><jupyter_text>Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code>x_values = pd.to_numeric(n_hem['Latitude']).astype(float)
y_values = pd.to_numeric(n_hem['Humidity']).astype(float)
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
regress_values = x_values * slope + intercept
line_equation = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
print("After performing the regression, there is no relationship between a city's latitude and the humidity in the Northern Hemisphere.")<jupyter_output><empty_output><jupyter_text>Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code>x_values = pd.to_numeric(s_hem['Latitude']).astype(float)
y_values = pd.to_numeric(s_hem['Humidity']).astype(float)
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
regress_values = x_values * slope + intercept
line_equation = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
print("After performing the regression, there is no relationship between a city's latitude and the humidity in the Southern Hemisphere.")<jupyter_output><empty_output><jupyter_text>Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code>x_values = pd.to_numeric(n_hem['Latitude']).astype(float)
y_values = pd.to_numeric(n_hem['Cloudiness']).astype(float)
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
regress_values = x_values * slope + intercept
line_equation = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
print("After performing the regression, there is no relationship between a city's latitude and the cloudiness in the Northern Hemisphere.")<jupyter_output><empty_output><jupyter_text>Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code>x_values = pd.to_numeric(s_hem['Latitude']).astype(float)
y_values = pd.to_numeric(s_hem['Cloudiness']).astype(float)
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
regress_values = x_values * slope + intercept
line_equation = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
print("After performing the regression, there is no relationship between a city's latitude and the cloudiness in the Southern Hemisphere.")<jupyter_output><empty_output><jupyter_text>Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code>x_values = pd.to_numeric(n_hem['Latitude']).astype(float)
y_values = pd.to_numeric(n_hem['Wind Speed']).astype(float)
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
regress_values = x_values * slope + intercept
line_equation = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
print("After performing the regression, there is a very weak relationship between a city's latitude and the wind speed in the Northern Hemisphere.")<jupyter_output><empty_output><jupyter_text>Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code>x_values = pd.to_numeric(s_hem['Latitude']).astype(float)
y_values = pd.to_numeric(s_hem['Wind Speed']).astype(float)
(slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
regress_values = x_values * slope + intercept
line_equation = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
print("After performing the regression, there is a very weak relationship between a city's latitude and the wind speed in the Southern Hemisphere.")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10945041257979138, 'fraction_numerical': 0.006305464736104624, 'mean_word_length': 5.833510638297873, 'pattern_counts': {'":': 9, '<': 74, '<?xml version=': 0, '>': 77, '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': '127964', 'license': 'ADSL', 'n_tokens_mistral': 4296, 'n_tokens_neox': 4046, 'n_words': 1260, 'path': 'starter_code/WeatherPy_final.ipynb', 'repo_name': '104ambrown/python-api-challenge', 'size': '12846'}