<jupyter_start><jupyter_text>Module 6 Challenge Part 1: Get the Weather Description and Amount of Precipitation for Each City<jupyter_code>from citipy import citipy
import numpy as np
import pandas as pd
# Create a set of random latitude and longitude 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)
lat_lngs 
# Add the Latitude and Longitudes to a list.
coordinates = list(lat_lngs)
# Create a list for holding the cities.
cities = []

# Identify nearest city for each latitude and longitude combination.
for coordinate in coordinates:
    city = citipy.nearest_city(coordinate[0], coordinate[1]).city_name
    
    # If the city is unique, add it to the cities list.
    if city not in cities:
        cities.append(city)
        
len(cities)
# Import the request library.
import requests

from datetime import datetime
from config import weather_api_key
# Starting URL for Weather Map API Call.
url = f"http://api.openweathermap.org/data/2.5/weather?units=Imperial&APPID={weather_api_key}"
# List of city data.
city_data = []

# Print to logger.
print('Beginning Data Retrieval')
print('-' * 25)

# Create a counter.
record_count = 1
set_count = 1
for index, city in enumerate(cities):
    
    # Group cities in sets of 50 for logging purposes.
    if(index % 50 == 0 and index >= 50):
        set_count += 1
        record_count = 1
        
    # Create endpoint URL with each city.
    city_url = f"{url}&q={city.replace(' ', '+')}"
    
    print(f"Processing Record {record_count} of Set {set_count} | {city}")
    
    record_count += 1
    
    try:
        city_weather = requests.get(city_url).json()
        # Parse out the max temp, humidity, and cloudiness.
        city_lat = city_weather['coord']['lat']
        city_lng = city_weather['coord']['lon']
        city_max_temp = city_weather['main']['temp_max']
        city_humidity = city_weather['main']['humidity']
        city_clouds = city_weather['clouds']['all']
        city_wind = city_weather['wind']['speed']
        city_country = city_weather['sys']['country']
        city_weather_description = city_weather['weather'][0]['description']
        try:
            city_rain_inches = city_weather['rain']['1h']
        except KeyError:
            city_rain_inches = 0
        try:
            city_snow_inches = city_weather['snow']['1h']
        except KeyError:
            city_snow_inches = 0
            
        # Append the city information into city_data.
        city_data.append(
        {
            'City': city,
            'Lat': city_lat,
            'Lng': city_lng,
            'Max Temp': city_max_temp,
            'Current Description': city_weather_description,
            'Rain (inches)': city_rain_inches,
            'Snow (inches)': city_snow_inches,
            'Humidity': city_humidity,
            'Cloudiness': city_clouds,
            'Wind Speed': city_wind,
            'Country': city_country
        })
    except:
        print('City not found. Skipping...')
        pass
# Indicate that the Data Loading is complete.
print('-' * 20)
print('Data Retrieval Complete')
print('-' * 20)
len(city_data)
# convert list of dictionaries to a pandas DataFrame
city_data_df = pd.DataFrame(city_data)
city_data_df.head(10)
# Reorder the columns in the order you want them to appear.
new_column_order = ['City', 'Country', 'Lat', 'Lng', 'Max Temp', 'Humidity', 
                    'Cloudiness', 'Wind Speed', 'Current Description', 
                    'Rain (inches)', 'Snow (inches)']

# Assign a new or the same DataFrame the new column order.
city_data_df = city_data_df[new_column_order]
city_data_df.head(10)
raining_cities = city_data_df.loc[city_data_df['Rain (inches)'] > 0]
raining_cities.head()
snowing_cities = city_data_df.loc[city_data_df['Snow (inches)'] > 0]
snowing_cities
# Create the output file (CSV).
output_data_file = 'challenge_data/WeatherPy_database.csv'
# Export the City_Data into a CSV.
city_data_df.to_csv(output_data_file, index_label='City_ID')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1116222760290557, 'fraction_numerical': 0.015738498789346248, 'mean_word_length': 3.1392785571142285, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 8, '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': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '393821', 'license': 'MIT', 'n_tokens_mistral': 1396, 'n_tokens_neox': 1294, 'n_words': 358, 'path': 'Weather_Database/Weather_Database.ipynb', 'repo_name': 'amayes824/World_Weather_Analysis', 'size': '4130'}