<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
import scipy.stats as stats
from scipy.stats import linregress

# Import API key
from api_keys import *

# 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>city_info = []

url = "http://api.openweathermap.org/data/2.5/weather?"
counter = 0
for city in cities: #[:10]:
   
    # Build query URL
    query_url = url + "appid=" + weather_api_key + "&q=" + city
    response = requests.get(query_url).json()
    
    counter=counter+1
    #print(query_url)
    
    try:
        city_num = counter
        city = response["name"]
        country = response["sys"]["country"]
        lat = response["coord"]["lat"]
        lng = response["coord"]["lon"]
        date = response["dt"]
        maxtemp = response["main"]["temp_max"]
        windspeed = response["wind"]["speed"]
        humidity = response["main"]["humidity"]
        cloudiness = response["clouds"]["all"]

        city_info.append([city_num, city, country, date, humidity, cloudiness, lat, lng, maxtemp, windspeed])
        print(f"Counter  {counter} {city}")
        time.sleep(.2)
    except:
        print("City not found")<jupyter_output><empty_output><jupyter_text>Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame<jupyter_code>#write df to file
clean_city_data_df.to_csv('../Resources/city_output.csv')

city_data_df = pd.DataFrame(city_info, columns=["city_num","city", "country", "date", "humidity", "cloudiness","lat", "long", "maxtemp", "windspeed"])
city_data_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>hum_info = 0
hum_info = city_data_df.loc[city_data_df.humidity > 100]
hum_info
#  Get the indices of cities that have humidity over 100%.
# none found
if (len(hum_info) != 0):
    print(hum_info.index)
hum_info
# 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".
if (len(hum_info) != 0):
   # for x in hum_info iterows:
   # for index, row in hum_info.iterrows():
        clean_city_data_df = city_data_df.drop(hum_info.index)
       # city_data_df.loc[index, row]
else:
    clean_city_data_df = city_data_df.copy()
clean_city_data_df<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.<jupyter_code># Generate a scatter plot of city data
x_values = clean_city_data_df['city_num']
y_values = clean_city_data_df['humidity']

plt.scatter( x_values, y_values, marker="*", facecolors="red", edgecolors="black")
plt.xlabel('city') 
plt.ylabel('humidity')
plt.title( "City Humidity")
plt.savefig("../images/city_humidity.png")
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Temperature Plot<jupyter_code># Generate a scatter plot of city data
x_values = clean_city_data_df['lat']
y_values = clean_city_data_df['maxtemp']

plt.scatter(x_values, y_values, marker="o", facecolors="red", edgecolors="black")
plt.xlabel('Latitude')
plt.ylabel('max temperature')
plt.savefig("../images/temp_lat.png")
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Humidity Plot<jupyter_code># Generate a scatter plot of city data
x_values = clean_city_data_df['lat']
y_values = clean_city_data_df['humidity']

plt.scatter(x_values, y_values)
plt.xlabel('lat')
plt.ylabel('humidity')
plt.savefig("../images/humidity_lat.png")
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Cloudiness Plot<jupyter_code># Generate a scatter plot of city data
x_values = clean_city_data_df['lat']
y_values = clean_city_data_df['cloudiness']

plt.scatter(x_values, y_values)
plt.xlabel('lat')
plt.ylabel('cloudiness')
plt.savefig("../images/cloud_lat.png")

plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Wind Speed Plot<jupyter_code># Generate a scatter plot of city data
x_values = clean_city_data_df['lat']
y_values = clean_city_data_df['windspeed']

plt.scatter(x_values, y_values)
plt.xlabel('lat')
plt.ylabel('windspeed')
plt.savefig("../images/windspeed_lat.png")
plt.show()<jupyter_output><empty_output><jupyter_text>Linear Regression<jupyter_code># plt.figure(figsize=(20,3))
# Generate a scatter plot of city data

x_values = clean_city_data_df['lat']
y_values = clean_city_data_df['windspeed']

(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-")
plt.annotate(line_eq,(6,10),fontsize=15,color="red")
plt.xlabel('latitude')
plt.ylabel('windspeed')
plt.savefig("../images/windspeed_lat_linear.png")
plt.show()<jupyter_output><empty_output><jupyter_text>Northern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code>x_values = clean_city_data_df['lat']
for x in x_values:
    if x >= 0:
        y_values = clean_city_data_df['maxtemp']

        (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-")
        plt.annotate(line_eq,(6,10),fontsize=15,color="red")
        plt.xlabel('latitude')
       

plt.ylabel('Max Temperature')
plt.title("Northern Hemisphere - Max Temp vs. Latitude Linear Regression")
plt.savefig("../images/maxtemp_lat_linear_N.png")
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12609238451935081, 'fraction_numerical': 0.00887779164932723, 'mean_word_length': 5.2155172413793105, 'pattern_counts': {'":': 0, '<': 49, '<?xml version=': 0, '>': 53, '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': '12', 'dir': 'jupyter-structured-clean-dedup', 'id': '109856', 'license': 'ADSL', 'n_tokens_mistral': 2606, 'n_tokens_neox': 2503, 'n_words': 601, 'path': 'WeatherPy/WeatherPy.ipynb', 'repo_name': 'kdturner83/PythonAPI_Challenge', 'size': '7209'}