<jupyter_start><jupyter_text>Reflect Tables into SQLAlchemy ORM<jupyter_code># Python SQL toolkit and Object Relational Mapper
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func, inspect
# create engine to hawaii.sqlite
engine = create_engine("sqlite:///Resources/hawaii.sqlite")
# reflect an existing database into a new model
Base = automap_base()
#reflect tables
Base.prepare(engine, reflect=True)
# View all of the classes that automap found
Base.classes.keys()
# Save references to each table
Measurement = Base.classes.measurement
Station = Base.classes.station
# Create our session (link) from Python to the DB
#create session 
session = Session(engine)
# create inspector
inspector=inspect(engine)
#Lets get some meta data to work with 
stations=engine.execute('select * from station')
print(stations.keys())
stations.fetchall()
columns=inspector.get_columns('Station')
for column in columns:
    print(column['name'], column['type'])
measurements=engine.execute('select * from measurement')
print(measurements.keys())
measurements.fetchall()
columns=inspector.get_columns('Measurement')
for column in columns:
    print(column['name'], column['type'])<jupyter_output>id INTEGER
station TEXT
date TEXT
prcp FLOAT
tobs FLOAT<jupyter_text>Exploratory Precipitation Analysis<jupyter_code># Find the most recent date in the data set.
latest_date=(session.query(Measurement.date)
                    .order_by(Measurement.date.desc())
                    .first())
latest_date
# Design a query to retrieve the last 12 months of precipitation
# data and plot the results. 
# Starting from the most recent data point in the database. 
year_ago_date=dt.date(2017, 8, 23) - dt.timedelta(days=366)
print('Query Date:', year_ago_date)
# Query for last 12 months data
year_prcp=(session.query(Measurement.date,func.max(Measurement.prcp))
                  .filter(func.strftime('%Y-%m-%d',Measurement.date) > year_ago_date)
                  .group_by(Measurement.date)
                  .all())
year_prcp
# Save the query results as a Pandas DataFrame and set the index to the date column
prcp_df=pd.DataFrame(year_prcp, columns=['date', 'prcp'])
prcp_df.set_index('date',inplace=True)
prcp_df.head(10)
# Sort the dataframe by date
prcp_df.sort_values('date')
# Starting with a data set
year_prcp_stats=(session.query(Measurement.date, Measurement.prcp)
                        .filter(Measurement.date > year_ago_date)
                        .all())
year_prcp_stats
# Use Pandas Plotting with Matplotlib to plot the data
year_prcp_stats_df=pd.DataFrame(year_prcp_stats, columns=['date', 'prcp'])
year_prcp_stats_df
year_prcp_stats_df.dropna()
# Use Pandas Plotting with Matplotlib to plot the data
plt.rcParams['figure.figsize']=(15,7)
prcp_df.plot(linewidth=2,alpha=1,rot=0, 
             xticks=(0,60,120,180,240,300,365),
             color='darkgray')

plt.xlim(-5,370)
plt.ylim(-0.4,7)
plt.yticks(size=14)
plt.xticks(fontsize=16)
plt.legend('',frameon=False)
plt.xlabel('12 Month Timeline',fontsize=20,color='black',labelpad=20)
plt.ylabel('Precipitation',fontsize=20,color='black',labelpad=20)
plt.title('Precipitation Over the Past 12 Months\nFrom Lastest Date in the Data Set',color='Black',fontsize=24,pad=40)

plt.show()
# Use Pandas to calcualte the summary statistics for the precipitation data
year_prcp_stats_df.describe()<jupyter_output><empty_output><jupyter_text>Exploratory Station Analysis<jupyter_code># Design a query to calculate the total number stations in the dataset
total_stations=session.query(Station).count()
print(f'There are {total_stations} stations')
# Design a query to find the most active stations (i.e. what stations have the most rows?)
# List the stations and the counts in descending order.
station_activity=(session.query(Measurement.station,func.count(Measurement.station))
                         .group_by(Measurement.station)
                         .order_by(func.count(Measurement.station).desc())
                         .all())
station_activity
# Using the most active station id from the previous query,
# calculate the lowest, highest, and average temperature.
# Start with a new list
tobs=[Measurement.station, 
             func.min(Measurement.tobs), 
             func.max(Measurement.tobs), 
             func.avg(Measurement.tobs)]

most_active_station=(session.query(*tobs)
                       .filter(Measurement.station=='USC00519281')
                       .all())
most_active_station
most_active_station_temp=pd.DataFrame(most_active_station, columns=['station', 'min_temp', 
                                                          'max_temp', 'avg_temp'])
most_active_station_temp.set_index('station', inplace=True)
most_active_station_temp
# Using the most active station id
# Query the last 12 months of temperature observation data for this station and plot the results as a histogram
year_tobs=(session.query(Measurement.date,(Measurement.tobs))
                  .filter(func.strftime(Measurement.date) > year_ago_date)
                  .filter(Measurement.station=='USC00519281')
                  .all())
year_tobs
tobs_df=pd.DataFrame(year_tobs)
tobs_df.set_index('date',inplace=True)

plt.rcParams['figure.figsize']=(8,4)
plt.hist(tobs_df['tobs'],bins=12,alpha=0.6,edgecolor='white',
         linewidth=1,color='darkgray')

plt.title('Temperature Observation Data\nPast 12 Months\nMost Active Station',fontsize=16,pad=40)
plt.xlabel('Temperature (F)',fontsize=12,color='black',labelpad=20)
plt.ylabel('Frequency',fontsize=12,color='black',labelpad=20)
plt.xticks(fontsize=9)
plt.yticks(fontsize=9)
plt.ylim(0,70)

plt.show()<jupyter_output><empty_output><jupyter_text>Close session<jupyter_code># Close Session
session.close()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11198765220373864, 'fraction_numerical': 0.0190361859029326, 'mean_word_length': 4.49670122525919, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 19, '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': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '266236', 'license': 'ADSL', 'n_tokens_mistral': 1935, 'n_tokens_neox': 1800, 'n_words': 423, 'path': 'jupiter-notebook/Climate.ipynb', 'repo_name': 'JohnHopkinsJr/sqlalchemy-challenge', 'size': '5831'}