<jupyter_start><jupyter_text>Generate City List<jupyter_code># Create list that will hold latitudes and longitudes
lat_lngs = []

# Create list that will hold, city names
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)
for lat_lng in lat_lngs:
    city = citipy.nearest_city(lat_lng[0], lat_lng[1]).city_name
    
    # append unique city names to city list
    if city not in cities:
        cities.append(city)
lat_lngs_list = list(lat_lngs)
print(len(cities))
url = "http://api.openweathermap.org/data/2.5/weather?units=Imperial&"

# Lists for storing values
cloudiness = []
country = []
date = []
max_temp = []
humidity = []
lat = []
lng = []
wind_speed = []
city_name = []

import sys
sys.path.append('../../')

import config 
from config import weather_api_key



# Loop through cities making the API call
i = 1
for city in cities:
    city=city
    query_url = url + "appid=" + weather_api_key + "&q=" + city
    response = requests.get(query_url).json()
    
    # extracting data and cleaning data
# print cleaned data
    try:
        
        cloudiness.append(response["clouds"]["all"])
        country.append(response["sys"]["country"])
        date.append(response["dt"])
        max_temp.append(response["main"]['temp_max'])
        humidity.append(response["main"]['humidity'])
        lat.append(response["coord"]["lat"])  
        lng.append(response["coord"]["lon"])
        wind_speed.append(response["wind"]["speed"])
        city_name.append(response["name"])
        print(f"Processing record {i}|{city}")
        i+=1
    except (KeyError):
        print("City name not found.")
# List for holding lat_lngs and cities
lat_lngs = []
cities = []
lat_range = (-90, 90)
lng_range = (-180, 180)

# 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)
#zip makes tuples from lats and lngs. If they are in the same position in both lists, they become paired as a tuple 
lat_lngs = zip(lats, lngs)
print("pulling cities and countries based off of the latitudes and longitudes generated")
# 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)
        
len(cities)<jupyter_output><empty_output><jupyter_text>API Calls<jupyter_code>#import api key
lng_lat = []
cities = []
 

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

sample_size = 500
location_data = pd.DataFrame()
location_data['lat_values'] = [np.random.uniform(-90,90) for x in range(1500)]
location_data['lng_values'] = [np.random.uniform(-180, 180) for x in range(1500)]
lat_lng = zip(lat, lng)

# Identify nearest city for each lat, lng combination
for x in lat_lngs:
    city = citipy.nearest_city(x[0], x[1]).city_name
if city not in cities:
        cities.append(city)
len(cities)
location_data.head()
#try replacing with lat /lng
record = 0
for index, row in location_data.iterrows():
    city_name = row['city']
    country_code = row['country']
    url = target_url + city_name + ',' + country_code + '&units=' + units + '&APPID=' + api_key
    print (url)
location_data['city'] = ""
location_data['country'] = ""

count = 0
for index, row in location_data.iterrows():
    near_city = citipy.nearest_city(row['lat_values'], row['lng_values']).city_name
    near_country = citipy.nearest_city(row['lat_values'], row['lng_values']).country_code
    location_data.loc(axis=0)[index,"city",near_city]
    location_data.loc(axis=0)[index,"country",near_country]
location_data.head()
# Create empty lists to append the API data into lists 
city_name = []
cloudiness = []
country = []
date = []
humidity = []
lat = []
lng = []
max_temp = []
wind_speed = []
countries =[]

# Start the call counter 
record = 1

print('''

Beginning API Call
--------------------------''')

#Loop through the cities pulled and stored in the cities list
for city in cities:  
    
    # Try statement to append calls where value is found because they won't all be in the OpenWeatherMap
    
    try: 
        response = requests.get(f"{base_url}&q={city}").json() 
        city_name.append(response["name"])
        cloudiness.append(response["clouds"]["all"])
        countries.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"])
        city_record = response["name"]
        print(f"Processing Record Number: {record} | {city_record}")
        print(f"{base_url}&q={city}")
        
        # Increases the counter by 1
        record= record + 1
        
    # skips to another call if a record isn't found
    except:
        print("City not found. Moving on to next call")
    continue
print(f"Pull done. {len(city_name)} cities found.")
ncities = 500
namsel = []
idsel = []
countrysel = []
latsel = []
lonsel = []
i = 0
while(i < ncities):
    i = i+1
    latitude = random.uniform(-90.0,90.0)
    longitude = random.uniform(-180.0,180.0)
    city = citipy.nearest_city(latitude,longitude)
    try:
        id = int(dfcities.loc[city.city_name]['id'])
        try:
            itemp = idsel.index(id)
            i = i - 1
        except:
            idsel.append(id)
            namsel.append(city.city_name)
            countrysel.append(dfcities.loc[city.city_name]['Country'])
            latsel.append(dfcities.loc[city.city_name]['Lat'])
            lonsel.append(dfcities.loc[city.city_name]['Lng'])
    except:
        i = i - 1

dftemp = pd.DataFrame({'City':namsel,'id':idsel,'Country':countrysel,'Lat':latsel,'Lng':lonsel})
dftemp.to_csv("output_data/dfselected.csv", index=False, header=True)
# WeatherPy_df.count()

# Initialize data frame to store data from API calls
WeatherPy_df =pd.DataFrame(columns = ["City","Cloudiness", "Country",
                                    "Date", "Max Temp", "Wind Speed", 
                                    "Lat","Lng", "Humidity"])
cities = pd.read_csv("output_data/cities.csv", encoding="utf-8")
cities.head()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14642313546423136, 'fraction_numerical': 0.017351598173515982, 'mean_word_length': 3.430883344571814, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '241837', 'license': 'ADSL', 'n_tokens_mistral': 2285, 'n_tokens_neox': 2211, 'n_words': 519, 'path': 'WeatherPy/.ipynb_checkpoints/WeatherPy-checkpoint.ipynb', 'repo_name': 'Tirhas-source/python-api-challenge', 'size': '6570'}