<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).<jupyter_code># OpenWeatherMap API Key
#api_key = api_keys.api_key

# Starting URL for Weather Map API Call
url = "http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=" + weather_api_key +"&q="

#Cities weather data frame
Cities_DF = pd.DataFrame({"City":cities})
Cities_DF["Temperature(F)"] =""
Cities_DF["Humidity(%)"] =""
Cities_DF["Cloudiness(%)"] =""
Cities_DF["Wind Speed(mph)"] =""
Cities_DF["Latitude"]=""
Cities_DF["Longitude"]=""
Cities_DF["Date"]=""
Cities_DF.head()
print("Beginning Data Retrieval")
print("------------------------")

for index, row in Cities_DF.iterrows():
    
    time.sleep(.8)
    city =row["City"]
    response = requests.get(url+city)
    city_weather = response.json()
    print(f"Processing Record {index} | {city}")
    city_weather_url =response.url
    #print(response.url)

    
    try:
        Cities_DF.loc[index,"Temperature(F)"]=city_weather['main']['temp']
        Cities_DF.loc[index,"Humidity(%)"]=city_weather['main']['humidity']
        Cities_DF.loc[index,"Cloudiness(%)"]=city_weather['clouds']['all']
        Cities_DF.loc[index,"Wind Speed(mph)"]=city_weather['wind']['speed']
        Cities_DF.loc[index,"Latitude"]=city_weather['coord']['lat']
        Cities_DF.loc[index,"Longitude"]=city_weather["coord"]['lon']
        Cities_DF.loc[index,"Date"]=city_weather["dt"]
        
    except (KeyError, IndexError):
        print(f"City not found... skipping.")

print("------------------------")
print("Data Retrieval Complete")
print("------------------------")

print(Cities_DF)<jupyter_output>Beginning Data Retrieval
------------------------
Processing Record 0 | vaini
Processing Record 1 | saleaula
City not found... skipping.
Processing Record 2 | korla
Processing Record 3 | belaya gora
Processing Record 4 | cidreira
Processing Record 5 | saint-philippe
Processing Record 6 | norman wells
Processing Record 7 | tsihombe
City not found... skipping.
Processing Record 8 | puerto narino
Processing Record 9 | busselton
Processing Record 10 | nikolskoye
Processing Record 11 | aberdeen
Processing Record 12 | sur
Processing Record 13 | male
Processing Record 14 | isangel
Processing Record 15 | lebu
Processing Record 16 | ankazoabo
Processing Record 17 | illoqqortoormiut
City not found... skipping.
Processing Record 18 | cobija
Processing Record 19 | mataura
Processing Record 20 | longyearbyen
Processing Record 21 | mullaitivu
City not found... skipping.
Processing Record 22 | havre-saint-pierre
Processing Record 23 | port alfred
Processing Record 24 | mar del plata
Processing Record[...]<jupyter_text>Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame<jupyter_code>Cities_DF.dropna(axis=0, inplace=True)

Cities_DF.to_csv('city_data_output.csv')
Cities_DF.head()
Cities_DF["Lat"] = pd.to_numeric(Cities_DF["Latitude"],errors='coerce')
Cities_DF["Lng"] = pd.to_numeric(Cities_DF["Longitude"],errors='coerce')
Cities_DF["Max Temp(%)"] = pd.to_numeric(Cities_DF["Temperature(F)"],errors='coerce')
Cities_DF["Humidity"] = pd.to_numeric(Cities_DF["Humidity(%)"],errors='coerce')
Cities_DF["Cloudiness(F)"] = pd.to_numeric(Cities_DF["Cloudiness(%)"],errors='coerce')
Cities_DF["Wind Speed"] = pd.to_numeric(Cities_DF["Wind Speed(mph)"],errors='coerce')
Cities_DF["Date"] = pd.to_numeric(Cities_DF["Date"],errors='coerce')

Cities_DF.describe()
# Get index names for humidity > 100%
index_names = Cities_DF[Cities_DF['Humidity'] >= 100].index

#drop these rows
Cities_DF.drop(index_names,inplace=True)
Cities_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># 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".


# Get index names for humidity > 100%
index_names = Cities_DF[Cities_DF['Humidity'] >= 100].index

#drop these rows
clean_city_data = Cities_DF.drop(index_names,inplace=False)
clean_city_data
clean_city_data.dtypes<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>#Latitude vs Temperature Plot
plt.title("City Latitude vs Temperature(F)")
plt.xlabel("Latitude")
plt.ylabel("Temperature(F)")
plt.grid()

plt.scatter(clean_city_data["Lat"],clean_city_data["Max Temp(%)"],edgecolors="black")
plt.savefig(f'../output_data/temp.png')
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs Temperature Scatter Plot InsightsThe plot maps 'cities' temperature against their latitude. The curve shows temperature increasing near the equator and dropping further away. The plot shows highers temperatures to right of the equator due to summer in northern hemisphere  Latitude vs. Humidity Plot<jupyter_code>#Latitude vs Humidity Plot
plt.title("City Latitude vs Humidity")
plt.xlabel("Latitude")
plt.ylabel("Humidity(%)")
plt.grid()

plt.scatter(clean_city_data["Lat"],clean_city_data["Humidity"],edgecolors="black")
plt.savefig(f'../output_data/humidity.png')
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs Humidity Scatter Plot InsightsThe plot maps 'cities' humidity against their latitude. There is no corelation between humidity and latitude  Latitude vs. Cloudiness Plot<jupyter_code>#Latitude vs Cloudiness Plot
plt.title("City Latitude vs Cloudiness(%)")
plt.xlabel("Latitude")
plt.ylabel("Cloudiness(%)")
plt.grid()

plt.scatter(clean_city_data["Lat"],clean_city_data["Cloudiness(F)"],edgecolors="black")

plt.savefig(f'../output_data/cloudiness.png')
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs Cloudiness Scatter Plot InsightsThe plot maps 'cities' cloudiness against their latitude. Cities selected randomlyThere is no obvious corelation between cloudiness and latitude. The plots are dense around 0% and 100% cloudiness  Latitude vs. Wind Speed Plot<jupyter_code>#Latitude vs Wind Speed Plot
plt.title("City Latitude vs Wind Speed(mph)")
plt.xlabel("Latitude")
plt.ylabel("Wind Speed(mph)")
plt.grid()

plt.scatter(clean_city_data["Lat"],clean_city_data["Wind Speed"],edgecolors="black")
plt.savefig(f'../output_data/wind.png')
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs Wind Speed Scatter Plot InsightsThe plot maps 'cities' Wind Speed against their latitude. Cities selected randomlyThere is no obvious corelation between Windspeed and latitude. The plots are dense around 0to 20 mph windspeed  Linear Regression<jupyter_code>#Create Northern and Southers Hemisphere Data Frames
north_df = Cities_DF.loc[Cities_DF["Lat"] > 0]
south_df = Cities_DF.loc[Cities_DF["Lat"] < 0]

#create Linear regression function
def linearreg(x_values,y_values,EQplotx,EQploty,y_label):
    (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-")
    print(f'The r square if {rvalue}')
    print(line_eq)
    plt.annotate(line_eq,(EQplotx,EQploty),fontsize=10,color="red")
    plt.xlabel('Latitude')
    plt.ylabel(f'{y_label}')
    plt.grid()<jupyter_output><empty_output><jupyter_text>Northern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code>#set the data sets
x_values = north_df["Lat"]
y_values = north_df["Max Temp(%)"]

#position equation
EQplotx  = 0
EQploty = -40

y_label = "Temperature (F)"
plt.title(f'Northern Hemishphere Latitude vs Temp')
          
linearreg(x_values,y_values,EQplotx,EQploty,y_label)

#save file
plt.savefig(f'../output_data/Northern Hemisphere Latitude vs Temp.png')
plt.show()<jupyter_output>The r square if -0.8687064249124591
y = -1.3x + 93.15<jupyter_text>Southern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code>#set the data sets
x_values = south_df["Lat"]
y_values = south_df["Max Temp(%)"]

#position equation
EQplotx  = -55
EQploty = 85

y_label = "Temperature (F)"
plt.title(f'Southern Hemishphere Latitude vs Temp')
          
linearreg(x_values,y_values,EQplotx,EQploty,y_label)

#save file
plt.savefig(f'../output_data/Southern Hemisphere Latitude vs Temp.png')
plt.show()<jupyter_output>The r square if 0.6553140854442211
y = 0.42x + 80.83<jupyter_text>Northern/Southern vs Temp Linear Regression InsightsThe plot maps Northern and Southern 'cities' Temperature against their latitude. Cities selected randomlyThere is strong corelation between distance from the equator temperature. The closer the equator, the higher the temperature   Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code>#set the data sets
x_values = north_df["Lat"]
y_values = north_df["Humidity"]

#position equation
EQplotx  = 50
EQploty = 15

y_label = "Humidity (%)"
plt.title(f'Northern Hemishphere Latitude vs Humidity')
          
linearreg(x_values,y_values,EQplotx,EQploty,y_label)

#save file
plt.savefig(f'../output_data/Northern Hemisphere Latitude vs Humidity.png')
plt.show()<jupyter_output>The r square if 0.30891476307544147
y = 0.32x + 58.96<jupyter_text>Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code>#set the data sets
x_values = south_df["Lat"]
y_values = south_df["Humidity"]

#position equation
EQplotx  = -20
EQploty = 30

y_label = "Humidity (%)"
plt.title(f'Southern Hemishphere Latitude vs Humidity')
          
linearreg(x_values,y_values,EQplotx,EQploty,y_label)

#save file
plt.savefig(f'../output_data/Southern Hemisphere Latitude vs Humidity.png')
plt.show()<jupyter_output>The r square if 0.39963757688948476
y = 0.43x + 85.15<jupyter_text>Northern/Southern vs Humidity Linear Regression InsightsThe plot maps Northern and Southern 'cities' Humidity against their latitude. Cities selected randomlyThere is no corelation between latitude and humidity   Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code>#set the data sets
x_values = north_df["Lat"]
y_values = north_df["Cloudiness(F)"]

#position equation
EQplotx  = 50
EQploty = 25

y_label = "Cloudiness (F)"
plt.title(f'Northern Hemishphere Latitude vs Cloudiness')
          
linearreg(x_values,y_values,EQplotx,EQploty,y_label)

#save file
plt.savefig(f'../output_data/Northern Hemisphere Latitude vs Cloudiness.png')
plt.show()<jupyter_output>The r square if 0.21961126688000715
y = 0.44x + 38.7<jupyter_text>Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code>#set the data sets
x_values = south_df["Lat"]
y_values = south_df["Cloudiness(F)"]

#position equation
EQplotx  = -55
EQploty = 60

y_label = "Cloudiness (F)"
plt.title(f'Southern Hemishphere Latitude vs Cloudiness')
          
linearreg(x_values,y_values,EQplotx,EQploty,y_label)

#save file
plt.savefig(f'../output_data/Southern Hemisphere Latitude vs Cloudiness.png')
plt.show()<jupyter_output>The r square if 0.19783330572734323
y = 0.55x + 72.02<jupyter_text>Northern/Southern Latitude vs Cloudiness Linear Regression InsightsThe plot maps Northern and Southern 'cities' Cloudiness against their latitude. Cities selected randomlyThere is no corelation between latitude and cloudiness   Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code>#set the data sets
x_values = north_df["Lat"]
y_values = north_df["Wind Speed"]

#position equation
EQplotx  = 5
EQploty = 25

y_label = "Cloudiness (F)"
plt.title(f'Northern Hemishphere Latitude vs Wind Speed')
          
linearreg(x_values,y_values,EQplotx,EQploty,y_label)

#save file
plt.savefig(f'../output_data/Northern Hemisphere Latitude vs Wind Speed.png')
plt.show()<jupyter_output>The r square if 0.2169214257234315
y = 0.06x + 5.59<jupyter_text>Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code>#set the data sets
x_values = south_df["Lat"]
y_values = south_df["Wind Speed"]

#position equation
EQplotx  = -15
EQploty = 25

y_label = "Cloudiness (F)"
plt.title(f'Southern Hemishphere Latitude vs Wind Speed')
          
linearreg(x_values,y_values,EQplotx,EQploty,y_label)

#save file
plt.savefig(f'../output_data/Southern Hemisphere Latitude vs Wind Speed.png')
plt.show()<jupyter_output>The r square if -0.3070553806782465
y = -0.12x + 5.11