# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# ### HW3

# For this homework, you are a data scientist working for Pronto (before the end of their contract with the City of Seattle). Your job is to assist in determining how to do end-of-day adjustments in the number of bikes at stations so that all stations will have enough bikes for the next day of operation (as estimated by the weekday average for the station for the year). Your assistance will help in constructing a plan for each day of the week that specifies how many bikes should be moved from each station and how many bikes must be delievered to each station.
#
# Your assignment is to construct plots of the differences between 'from' and 'to' counts for each station by day of the week. Do this as a set of 7 subplots. You should use at least one function to construct your plots.

# #### Q1: create a dataframe with station counts averages by day-of-week

import pandas as pd
import matplotlib.pyplot as plt
# %matplotlib inline
import numpy as np

df = pd.read_csv("2015_trip_data.csv")
#df.head()

# Create time using DatetimeIndex method in pandas

time = pd.DatetimeIndex(df.starttime)

df["DoW"] = time.dayofweek
pd.value_counts(df["DoW"])

# Create data frames that contains the daily count of "from" and "to" records for each station respectively

df1F = df.groupby([time.date, 'DoW', 'from_station_id']).size().unstack()
df1T = df.groupby([time.date, 'DoW', 'to_station_id']).size().unstack()

df1F.head()

df1T.head()

# The daily difference at each station

diff = df1F - df1T

diff.head()

# Manupulation of the dataset to make the DayofWeek a column, in preparation for later aggregation

diff.reset_index(level=0, inplace = True)
diff.drop('level_0', axis = 1, inplace=True)
diff.reset_index(level=0, inplace = True)

diff_avg = diff.groupby('DoW').mean()

# drop 'Pronto shop' column

diff_avg.pop('Pronto shop')

# Data frame for question 1:

diff_avg.index = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']

diff_avg

# #### Q2: structure the 7 day-of-week plots as subplots
# #### Q3: label the plots by day-of-week
# #### Q4: label the x-axis for plots in the last row and label the y-axis for plots in the left-most column

diff_avg.transpose().head()

diff_avg.transpose().columns


def plot_bar1(df, column, opts):
    """
    Does a bar plot for a single column.
    :param pd.DataFrame df:
    :param str column: name of the column to plot
    :param dict opts: key is plot attribute
    """
    n_groups = len(df.index)
    index = np.arange(n_groups)  # The "raw" x-axis of the bar plot
    rects1 = plt.bar(index, df[column])
    if 'xlabel' in opts.keys():
      plt.xlabel(opts['xlabel'])
    else:
        pass
    if 'ylabel'in opts.keys():
      plt.ylabel(opts['ylabel'])
    else:
        pass
    if 'xticks' in opts.keys()  and opts['xticks']:
      plt.xticks(index, df.index)  # Convert "raw" x-axis into labels
      _, labels = plt.xticks()  # Get the new labels of the plot
      plt.setp(labels, rotation=90)  # Rotate labels to make them readable
    else:
      labels = ['' for x in df.index]
      plt.xticks(index, labels)   
    if 'ylim' in opts.keys():
      plt.ylim(opts['ylim'])
    if 'title' in opts.keys():
      plt.title(opts['title'])


def plot_barN(df, columns, opts):
    """
    Does a bar plot for a single column.
    :param pd.DataFrame df:
    :param list-of-str columns: names of the column to plot
    :param dict opts: key is plot attribute
    """
    num_columns = len(columns)
    local_opts = dict(opts)  # Make a deep copy of the object
    idx = 0
    for column in columns:
        idx += 1
        local_opts['xticks'] = False
        local_opts['xlabel'] = ''
        local_opts['title'] = column
        if idx == num_columns:
          local_opts['xticks'] = True
          local_opts['xlabel'] = opts['xlabel']
        plt.subplot(num_columns, 1, idx)
        plot_bar1(df, column, local_opts)


fig = plt.figure(figsize=(12, 16))  # Controls global properties of the bar plot
opts = {'xlabel': 'Stations', 'ylabel': 'Averages Difference'}
plot_barN(diff_avg.transpose(), ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], opts)

StarcoderdataJupyterScriptsDedupFiltered