<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 datetime import datetime
import openweathermapy.core as owm
import csv

# Import API key
from api_keys import 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
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_keys
url = "http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=" + api_key

#Create empty lists to append the API data into lists 
city_name = []
cloudiness = []
country = []
date = []
humidity = []
lat = []
lng = []
max_temp = []
wind_speed = []

count = 1 # counter to count the number of calls to API
err = 0 # error count to record how many cities the API responds back with no data.
sets = 1 # counter to count the number of call sets
index = 0
print(f'Beginning Data Retrieval \n ........................')
for city in cities:
    try:
        print(f'Processing Record {count} of Set {sets} | {city}' )
        print(f"{url}&q={city}")
        
    # Try statement to append calls where value is found 
    # Not all calls return data as OpenWeatherMap will not have have records in all the cities generated by CityPy module 
        response = requests.get(f"{url}&q={city}").json() 
        city_name.append(response["name"])
        cloudiness.append(response["clouds"]["all"])
        country.append(response["sys"]["country"])
        date.append(response["dt"])
        humidity.append(response["main"]["humidity"])
        max_temp.append(response["main"]["temp_max"])
        lat.append(response["coord"]["lat"])
        lng.append(response["coord"]["lon"])
        wind_speed.append(response["wind"]["speed"])
        
    except:
        print(f'City not found. Skipping...') 
        
        err= err+1
    count = count + 1
    if count == 51: # loop to limit 50 API calls per minute. The OpenWeatherMap API limit is 60 calls/min
        count = count + 1
        sets = (sets // 50) + 1
        # Wait a second in loop to not over exceed rate limit of API
        time.sleep(1.01)
print("-------------------------")
print(f'Data Retrieval Complete')
print("-------------------------")<jupyter_output>Beginning Data Retrieval 
 ........................
Processing Record 1 of Set 1 | bluff
http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=9f47e495713e79f40dcf331c6b90a28a&q=bluff
Processing Record 2 of Set 1 | klaksvik
http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=9f47e495713e79f40dcf331c6b90a28a&q=klaksvik
Processing Record 3 of Set 1 | ushuaia
http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=9f47e495713e79f40dcf331c6b90a28a&q=ushuaia
Processing Record 4 of Set 1 | conceicao do araguaia
http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=<KEY>a&q=conceicao do araguaia
Processing Record 5 of Set 1 | taolanaro
http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=9f47e495713e79f40dcf331c6b90a28a&q=taolanaro
City not found. Skipping...
Processing Record 6 of Set 1 | grand forks
http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID=9f47e495713e79f40dcf331c6b90a[...]<jupyter_text>Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame<jupyter_code># Create a dictonary with the lists generated
weatherpy_dict = {
    "City": city_name,
    "Cloudiness":cloudiness, 
    "Country":country,
    "Date":date, 
    "Humidity": humidity,
    "Lat":lat, 
    "Lng":lng, 
    "Max Temp": max_temp,
    "Wind Speed":wind_speed
}

# Create a data frame from dictionary
weather_data = pd.DataFrame(weatherpy_dict)

# Display count of weather data values 
weather_data.count()
# save to csv file
weather_data.to_csv("weather_data.csv", encoding='utf-8', index=False)

# Display the city weather data frame
weather_data.head(10)<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># Build a scatter plot for each data type
plt.scatter(weather_data["Lat"], weather_data["Max Temp"], marker="o", s=10)

# Incorporate the other graph properties
plt.title("Latitude vs. Temperature")
plt.ylabel("Max. Temperature (F)")
plt.xlabel("Latitude")
plt.grid(True)

# Show plot
plt.show()
# Save the figure
plt.savefig("City Latitude vs Temperature.png")<jupyter_output><empty_output><jupyter_text>Latitude vs. Humidity Plot<jupyter_code># Build a scatter plot for each data type
plt.scatter(weather_data["Lat"], weather_data["Humidity"], marker="o", s=10)

# Incorporate the other graph properties
plt.title("Latitude vs. Humidity")
plt.ylabel("Humidity (%)")
plt.xlabel("Latitude")
plt.grid(True)

# Show plot
plt.show()
# Save the figure
plt.savefig("Latitude vs Humidity.png")<jupyter_output><empty_output><jupyter_text>Latitude vs. Cloudiness Plot<jupyter_code># Build a scatter plot for each data type
plt.scatter(weather_data["Lat"], weather_data["Cloudiness"], marker="o", s=10)

# Incorporate the other graph properties
plt.title("Latitude vs. Cloudiness")
plt.ylabel("Cloudiness (%)")
plt.xlabel("Latitude")
plt.grid(True)

# Show plot
plt.show()
# Save the figure
plt.savefig("Latitude vs Cloudiness.png")<jupyter_output><empty_output><jupyter_text>Latitude vs. Wind Speed Plot<jupyter_code># Build a scatter plot for each data type
plt.scatter(weather_data["Lat"], weather_data["Wind Speed"], marker="o", s=10)

# Incorporate the other graph properties
plt.title("Latitude vs. Wind Speed")
plt.ylabel("Wind Speed (mph)")
plt.xlabel("Latitude")
plt.grid(True)

# Show plot
plt.show()
# Save the figure
plt.savefig("Latitude vs Wind Speed.png")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12589675059783373, 'fraction_numerical': 0.0282740188493459, 'mean_word_length': 4.382286146858441, 'pattern_counts': {'":': 9, '<': 33, '<?xml version=': 0, '>': 33, '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': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '138381', 'license': 'ADSL', 'n_tokens_mistral': 2539, 'n_tokens_neox': 2316, 'n_words': 676, 'path': 'Solution/WeatherPy.ipynb', 'repo_name': 'acanales92/Python-API-Challenge', 'size': '7135'}