<jupyter_start><jupyter_text><NAME>, Hmk 3  For this homework, 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.<jupyter_code>import pandas as pd
import numpy as np
import scipy
import seaborn
import matplotlib.pyplot as plt
# The following ensures that the plots are in the notebook
%matplotlib inline<jupyter_output><empty_output><jupyter_text>**Imported the Data**<jupyter_code>df_original = pd.read_csv("2015_trip_data.csv")<jupyter_output><empty_output><jupyter_text>Created four new columns with the days of the week and dates extracted from the starttime and stoptime for each row. Note: Not sure whether I should delete the rows with "Pronto shop" from the "original data frame," but given the goal and the fact that there were only a dozen or so mentions in the data, I decided to go ahead and delete the rows with trips to and from the "Pronto shop."<jupyter_code>df_original = df_original[df_original.from_station_name != "Pronto shop"]
df_original = df_original[df_original.to_station_name != "Pronto shop"]<jupyter_output><empty_output><jupyter_text>Add "day of week" and "date" columns to the original data frame to correspond with the "To" and "From" groups using the days of the week and the dates from the starttime and stoptime columns.<jupyter_code>df_original["from_day_of_week"] = pd.DatetimeIndex(df_original['starttime']).dayofweek
df_original["to_day_of_week"] = pd.DatetimeIndex(df_original['stoptime']).dayofweek
df_original["from_date"] = pd.DatetimeIndex(df_original['starttime']).date
df_original["to_date"] = pd.DatetimeIndex(df_original['stoptime']).date<jupyter_output><empty_output><jupyter_text>Check that the four new columns were added to the data frame.<jupyter_code>df_original.columns<jupyter_output><empty_output><jupyter_text>Counted the number of bikes going to and from each station on each day of the week, and counted the number of days in order to take the average. With groupby you can group by multiple values and use aggregation functions like mean, median, sum, minimum, maximum, standard deviation, or count: >  `.groupby().()`<jupyter_code># Create a groupby variable that groups stations by day of week 
# and counts the days of the week
toStation_day_count = df_original.groupby(["to_station_id", "to_day_of_week"])["to_day_of_week"].count()
toStation_day_count.head(3)
fromStation_day_count = df_original.groupby(["from_station_id", "from_day_of_week"])["from_day_of_week"].count()
fromStation_day_count.head(3)
to_day_count = df_original.groupby(['to_day_of_week','to_date']).size().reset_index()
to_day_count = to_day_count.groupby(['to_day_of_week'])['to_date'].count()
from_day_count = df_original.groupby(['from_day_of_week','from_date']).size().reset_index()
from_day_count = from_day_count.groupby(['from_day_of_week'])['from_date'].count()
to_avg_bikes = toStation_day_count / to_day_count
from_avg_bikes = fromStation_day_count / from_day_count
deltaBikesPerStation = to_avg_bikes.unstack() - from_avg_bikes.unstack()
deltaBikesPerStation.head(4)<jupyter_output><empty_output><jupyter_text>**Plotted the average difference bike counts per station per day of the week**<jupyter_code>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])
    plt.subplots_adjust(left=None, bottom=None, right=None, 
                    top=None, wspace=None, hspace=0.4)
    if 'xlabel' in opts:
      plt.xlabel(opts['xlabel'])
    if 'ylabel' in opts:
      plt.ylabel(opts['ylabel'])
    if ('xticks' and 'xticks') in opts:
      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:
      plt.ylim(opts['ylim'])
    if 'title' in opts:
      plt.title(opts['title'])
        
def plotNbar(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)
    days = ["Monday", "Tuesday", "Wednesday", 
            "Thursday", "Friday", "Saturday", "Sunday"]
    opts['title'] = days
    local_opts = dict(opts)  # Make a deep copy of the object
    local_opts['title'] = days
    idx = 0
    for column in columns:
        idx += 1
        local_opts['xticks'] = False
        local_opts['xlabel'] = ''
        local_opts['title'] = opts['title'][column]
        if idx == num_columns:
          local_opts['xticks'] = True
          local_opts['xlabel'] = opts['xlabel']
        plt.subplot(num_columns, 1, idx)
        # calls plot_bar1 to plot each column
        plot_bar1(df, column, local_opts)

seaborn.axes_style()
current_palette = seaborn.color_palette()
seaborn.palplot(seaborn.color_palette("GnBu_d"))
with seaborn.color_palette("RdBu_r", 7):
    seaborn.set_style("whitegrid", {"axes.facecolor": ".9"})
    fig = plt.figure(figsize=(20, 40))  # Controls global properties of the bar plot
    opts = {'xlabel': 'Stations', 
            'ylabel': 'Average Daily Bike Counts', 'ylim': [-12, 10]}
    plotNbar(deltaBikesPerStation, [0, 1, 2, 3, 4, 5, 6], opts)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10530572630216758, 'fraction_numerical': 0.005985118084762213, 'mean_word_length': 4.5602517985611515, 'pattern_counts': {'":': 1, '<': 30, '<?xml version=': 0, '>': 31, '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': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '581067', 'license': 'MIT', 'n_tokens_mistral': 2016, 'n_tokens_neox': 1954, 'n_words': 629, 'path': 'SEDS-HW3.ipynb', 'repo_name': 'UWSEDS/hw3-orbitse', 'size': '6187'}