<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
from pprint import pprint

# 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)
print(weather_api_key)<jupyter_output>768a8d905daa41f48c7da703c1eec953<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>weatherdata_df = pd.DataFrame({"City": cities, "Lat":"", "Lng":"", "Max Temp": "","Humidity": "",
                               "Cloudiness": "","Wind Speed": "","Country": "","Date": ""})


base_url = 'http://api.openweathermap.org/data/2.5/weather?units=imperial&q='

count = 1
batch = 1

# use iterrows to iterate through pandas dataframe
for index, row in weatherdata_df.iterrows():
    
    #creating URL to serach in API
    query_url = f'{base_url}{row["City"]},&APPID={weather_api_key}'
    
    
    #do the API call
    response = requests.get(query_url).json()
    #pprint(response)
   
    try:
        city = response["name"]
        print(f"Processing Record {count} of Set {batch} | {city}")
        
        weatherdata_df.loc[index, 'Country'] = response['sys']['country']
        weatherdata_df.loc[index, 'Max Temp'] = response['main']['temp_max']
        weatherdata_df.loc[index, 'Humidity'] = response['main']['humidity']
        weatherdata_df.loc[index, 'Cloudiness'] = response['clouds']['all']
        weatherdata_df.loc[index, 'Wind Speed'] = response['wind']['speed']
        weatherdata_df.loc[index, 'Lat'] = response['coord']['lat']
        weatherdata_df.loc[index, 'Lng'] = response['coord']['lon']
        weatherdata_df.loc[index, 'Date'] = response['dt']
               
        count += 1
    
    except (KeyError, IndexError):
        print("City not found.Skipping...")
        
    if count == 51:
        batch += 1
        count = 1<jupyter_output>Processing Record 1 of Set 1 | Pampierstad
Processing Record 2 of Set 1 | Jamestown
Processing Record 3 of Set 1 | Kapaa
Processing Record 4 of Set 1 | Vaini
Processing Record 5 of Set 1 | Lagoa
Processing Record 6 of Set 1 | Telde
Processing Record 7 of Set 1 | Lavrentiya
Processing Record 8 of Set 1 | Chui
City not found.Skipping...
Processing Record 9 of Set 1 | Yellowknife
Processing Record 10 of Set 1 | Ushuaia
Processing Record 11 of Set 1 | Castro
City not found.Skipping...
Processing Record 12 of Set 1 | Mehamn
Processing Record 13 of Set 1 | São Filipe
Processing Record 14 of Set 1 | Port Alfred
Processing Record 15 of Set 1 | Provideniya
Processing Record 16 of Set 1 | Chokurdakh
Processing Record 17 of Set 1 | São Francisco de Paula
Processing Record 18 of Set 1 | Rikitea
Processing Record 19 of Set 1 | Lebu
Processing Record 20 of Set 1 | Atuona
Processing Record 21 of Set 1 | Busselton
Processing Record 22 of Set 1 | Hobart
Processing Record 23 of Set 1 | ‘Āhuimanu
Process[...]<jupyter_text>Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame<jupyter_code>weatherdata_df = weatherdata_df.replace("", np.nan)
weatherdata_df = weatherdata_df.dropna()
weatherdata_df.count()<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%.
weatherdata_df = weatherdata_df[weatherdata_df.Humidity < 100]
weatherdata_df.head()<jupyter_output><empty_output><jupyter_text>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".<jupyter_code># Extract relevant fields from the data frame
city_data = weatherdata_df.copy()

# Export the City_Data into a csv
city_data.to_csv (r'C:\Users\njpat\OneDrive\Desktop\API - Python\starter_code\city_data.csv', index = False, header=True)<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_data["Lat"], city_data["Max Temp"], marker="o", facecolors="blue")

#Label the axis
plt.title(f'City Latitude vs. Max Temperature {time.strftime("%m/%d/%Y")}')
plt.xlabel("Latitude")
plt.ylabel("Temperature (F)")

plt.grid(True)

# Save the figure
plt.savefig("City Latitude vs. Max Temperature.png")

plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Humidity Plot<jupyter_code>plt.scatter(city_data["Lat"], city_data["Humidity"], marker="o", facecolors="blue")

#Label the axis
plt.title(f'City Latitude vs. Humidity {time.strftime("%m/%d/%Y")}')
plt.xlabel("Latitude")
plt.ylabel("Humidity (%)")

plt.grid(True)

# Save the figure
plt.savefig("City Latitude vs. Humidity.png")

plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Cloudiness Plot<jupyter_code>plt.scatter(city_data["Lat"], city_data["Cloudiness"], marker="o", facecolors="blue")

#Label the axis
plt.title(f'City Latitude vs. Cloudiness {time.strftime("%m/%d/%Y")}')
plt.xlabel("Latitude")
plt.ylabel("Cloudiness (%)")

plt.grid(True)

# Save the figure
plt.savefig("City Latitude vs.Cloudiness.png")

plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Wind Speed Plot<jupyter_code>plt.scatter(city_data["Lat"], city_data["Wind Speed"], marker="o", facecolors="blue")

#Label the axis
plt.title(f'City Latitude vs. Wind Speed {time.strftime("%m/%d/%Y")}')
plt.xlabel("Latitude")
plt.ylabel("Wind Speed (%)")

plt.grid(True)

# Save the figure
plt.savefig("City Latitude vs. Wind Speed.png")

plt.show()<jupyter_output><empty_output><jupyter_text>Linear Regression<jupyter_code># OPTIONAL: Create a function to create Linear Regression plots
def linreg(x, y, ax = -0.10, ay = 15):
    x_values = x
    y_values = y
    (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,(ax,ay),fontsize=15,color="red")
    print(f"The r-squared is: {rvalue**2}")

# Create Northern and Southern Hemisphere DataFrames
north_df = city_data[city_data.Lat >= 0]
south_df = city_data[city_data.Lat < 0]<jupyter_output><empty_output><jupyter_text>Northern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code>linreg(north_df["Lat"], north_df["Max Temp"], -0.10, 45)
plt.xlabel('Lattitude')
plt.ylabel('Max Temp')
plt.show()<jupyter_output>The r-squared is: 0.48345655625600487<jupyter_text>Southern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code>linreg(south_df["Lat"], south_df["Max Temp"], -21.5, 35)
plt.xlabel('Lattitude')
plt.ylabel('Max Temp')
plt.show()<jupyter_output>The r-squared is: 0.5592182404889401<jupyter_text>Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression  linreg(north_df["Lat"], north_df["Humidity"], 45, -2)plt.xlabel('Lattitude')plt.ylabel('Humidity (%)')plt.show()   Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code>linreg(south_df["Lat"], south_df["Humidity"], -25, -2)
plt.xlabel('Lattitude')
plt.ylabel('Humidity (%)')
plt.show()<jupyter_output>The r-squared is: 0.002031041625030568<jupyter_text>Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code>linreg(north_df["Lat"], north_df["Cloudiness"], 0, 5)
plt.xlabel('Lattitude')
plt.ylabel('Cloudiness (%)')
plt.show()<jupyter_output>The r-squared is: 0.012978015563967762<jupyter_text>Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code>linreg(south_df["Lat"], south_df["Cloudiness"], -50)
plt.xlabel('Lattitude')
plt.ylabel('Cloudiness (%)')
plt.show()<jupyter_output>The r-squared is: 0.013387863804943074<jupyter_text>Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code>linreg(north_df["Lat"], north_df["Wind Speed"], 0, 30)
plt.xlabel('Lattitude')
plt.ylabel('Wind Speed (mph)')
plt.show()<jupyter_output>The r-squared is: 1.7917585289375842e-05<jupyter_text>Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code>linreg(south_df["Lat"], south_df["Wind Speed"], -50, 21)
plt.xlabel('Lattitude')
plt.ylabel('Wind Speed (mph)')
plt.show()<jupyter_output>The r-squared is: 0.01456557936432266
{'fraction_non_alphanumeric': 0.128171031096563, 'fraction_numerical': 0.029869067103109655, 'mean_word_length': 5.295556986477785, 'pattern_counts': {'":': 9, '<': 66, '<?xml version=': 0, '>': 67, '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': '45439', 'license': 'ADSL', 'n_tokens_mistral': 3706, 'n_tokens_neox': 3308, 'n_words': 891, 'path': 'starter_code/WeatherPy.ipynb', 'repo_name': 'njpatel04/API-Challenge', 'size': '9776'}