# ---
# 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
# ---

# # Software Engineering for Data Scientists
#
# ## *Sophisticated Data Manipulation*
# ## DATA 515 A

# ## 1. Python's Data Science Ecosystem
#
# With this simple Python computation experience under our belt, we can now move to doing some more interesting analysis.

# ### Python's Data Science Ecosystem
#
# In addition to Python's built-in modules like the ``math`` module we explored above, there are also many often-used third-party modules that are core tools for doing data science with Python.
# Some of the most important ones are:
#
# #### [``numpy``](http://numpy.org/): Numerical Python
#
# Numpy is short for "Numerical Python", and contains tools for efficient manipulation of arrays of data.
# If you have used other computational tools like IDL or MatLab, Numpy should feel very familiar.
#
# #### [``scipy``](http://scipy.org/): Scientific Python
#
# Scipy is short for "Scientific Python", and contains a wide range of functionality for accomplishing common scientific tasks, such as optimization/minimization, numerical integration, interpolation, and much more.
# We will not look closely at Scipy today, but we will use its functionality later in the course.
#
# #### [``pandas``](http://pandas.pydata.org/): Labeled Data Manipulation in Python
#
# Pandas is short for "Panel Data", and contains tools for doing more advanced manipulation of labeled data in Python, in particular with a columnar data structure called a *Data Frame*.
# If you've used the [R](http://rstats.org) statistical language (and in particular the so-called "Hadley Stack"), much of the functionality in Pandas should feel very familiar.
#
# #### [``matplotlib``](http://matplotlib.org): Visualization in Python
#
# Matplotlib started out as a Matlab plotting clone in Python, and has grown from there in the 15 years since its creation. It is the most popular data visualization tool currently in the Python data world (though other recent packages are starting to encroach on its monopoly).

# # 2. Installation

# ### Installing Pandas & friends
#
# Because the above packages are not included in Python itself, you need to install them separately. While it is possible to install these from source (compiling the C and/or Fortran code that does the heavy lifting under the hood) it is much easier to use a package manager like ``conda``. All it takes is to run
#
# ```
# $ conda install numpy scipy pandas matplotlib
# ```
#
# and (so long as your conda setup is working) the packages will be downloaded and installed on your system.

# # 3. Arrays and slicing in Numpy

import numpy as np

# ### Lists in native Python
#
# Let's create a **list**, a native Python object that we've used earlier today.

my_list = [2, 5, 7, 8]
my_list

type(my_list)

# This list is one-dimensional, let's make it multidimensional!

multi_list = [[1, 2, 3], [4, 5, 6]]

# How do we access the *6* element in the second row, third column for native Python list?

# +
#
# -

# ### Converting to numpy Arrays

my_array = np.array(my_list)

type(my_array)

my_array.dtype

multi_array.shape

multi_array = np.array([[1, 2, 3], [4, 5, 6]], np.int32)

# How do we access the *6* element in the second row, third column for numpy array?

# +
#
# -

# How do we retrieve a slice of the array, `array([[1, 2], [4, 5]])`?

# +
#
# -

# How do we retrieve the second column of the array?

# +
#
# -

# ## 4. Introduction to Pandas DataFrames

# What are the elements of a table?

# Pandas DataFrames as table elements
import pandas as pd

# What operations do we perform on tables?

df = pd.DataFrame({'A': [1,2,3], 'B': [2, 4, 6], 'ccc': [1.0, 33, 4]})
df          

sub_df = df[['A', 'ccc']]
sub_df

df['A'] + 2*df['B']

# # Operations on a Pandas DataFrame

# ## 5. Manipulating Data with DataFrames

# ### Downloading the data
#
# Shell commands can be run from the notebook by preceding them with an exclamation point:

# !ls

# uncomment this to download the data:

# !curl -o pronto.csv https://data.seattle.gov/api/views/tw7j-dfaw/rows.csv?accessType=DOWNLOAD

# ### Loading Data into a DataFrame

# Because we'll use it so much, we often import under a shortened name using the ``import ... as ...`` pattern:

import pandas as pd
df = pd.read_csv('pronto.csv')

type(df)

len(df)

# Now we can use the ``read_csv`` command to read the comma-separated-value data:

# *Note: strings in Python can be defined either with double quotes or single quotes*

# ### Viewing Pandas Dataframes

# The ``head()`` and ``tail()`` methods show us the first and last rows of the data

df.head()

df.columns

df.index

smaller_df = df.loc[[1,4,6,7,9,34],:]


smaller_df.index

# The ``shape`` attribute shows us the number of elements:

df.shape

# The ``columns`` attribute gives us the column names

# The ``index`` attribute gives us the index names

# The ``dtypes`` attribute gives the data types of each column:

df.dtypes

# ### Sophisticated Data Manipulation
#
# Here we'll cover some key features of manipulating data with pandas

# Access columns by name using square-bracket indexing:

df_small = df['stoptime']

type(df_small)

df_small.tolist()

# Mathematical operations on columns happen *element-wise*:

trip_duration_hours = df['tripduration']/3600
trip_duration_hours[:2]

trip_duration_hours.head()

df['trip_duration_hours'] = df['tripduration']/3600

del df['trip_duration_hours']

df.head()

df.loc[[0,1],:]

df_long_trips = df[df['tripduration'] >10000]

sel = df['tripduration'] > 10000
df_long_trips = df[sel]

df_long_trips

df[sel].shape

# Make a copy of a slice
df_subset = df[['starttime', 'stoptime']].copy()
df_subset['trip_hours'] = df['tripduration']/3600

# Columns can be created (or overwritten) with the assignment operator.
# Let's create a *tripminutes* column with the number of minutes for each trip

# More complicated mathematical operations can be done with tools in the ``numpy`` package:

# ### Working with Times

# One trick to know when working with columns of times is that Pandas ``DateTimeIndex`` provides a nice interface for working with columns of times.
#
# For a dataset of this size, using ``pd.to_datetime`` and specifying the date format can make things much faster (from the [strftime reference](http://strftime.org/), we see that the pronto data has format ``"%m/%d/%Y %I:%M:%S %p"``

# (Note: you can also use ``infer_datetime_format=True`` in most cases to automatically infer the correct format, though due to a bug it doesn't work when AM/PM are present)

# With it, we can extract, the hour of the day, the day of the week, the month, and a wide range of other views of the time:

# ### Simple Grouping of Data
#
# The real power of Pandas comes in its tools for grouping and aggregating data. Here we'll look at *value counts* and the basics of *group-by* operations.

# #### Value Counts

# Pandas includes an array of useful functionality for manipulating and analyzing tabular data.
# We'll take a look at two of these here.

# The ``pandas.value_counts`` returns statistics on the unique values within each column.
#
# We can use it, for example, to break down rides by gender:

pd.value_counts(df["gender"])

# Or to break down rides by age:

pd.value_counts(2019 - df["birthyear"])

# By default, the values rather than the index are sorted. Use ``sort=False`` to turn this behavior off:

pd.value_counts(df["birthyear"], sort=False)

# We can explore other things as well: day of week, hour of day, etc.

# +
#
# -

# ### Group-by Operation
#
# One of the killer features of the Pandas dataframe is the ability to do group-by operations.
# You can visualize the group-by like this (image borrowed from the [Python Data Science Handbook](http://shop.oreilly.com/product/0636920034919.do))

df.head()

df_count = df.groupby(['from_station_id']).count()
df_count.head()

df_mean = df.groupby(['from_station_id']).mean()
df_mean.head()

dfgroup = df.groupby(['from_station_id'])
dfgroup.groups

# The simplest version of a groupby looks like this, and you can use almost any aggregation function you wish (mean, median, sum, minimum, maximum, standard deviation, count, etc.)
#
# ```
# <data object>.groupby(<grouping values>).<aggregate>()
# ```
#
# for example, we can group by gender and find the average of all numerical columns:

df.groupby(gender).mean()

# It's also possible to index the grouped object like it is a dataframe:



# You can even group by multiple values: for example we can look at the trip duration by time of day and by gender:



# The ``unstack()`` operation can help make sense of this type of multiply-grouped data. What this technically does is split a multiple-valued index into an index plus columns:



# ### Visualizing data with ``pandas``
#
# Of course, looking at tables of data is not very intuitive.
# Fortunately Pandas has many useful plotting functions built-in, all of which make use of the ``matplotlib`` library to generate plots.
#
# Whenever you do plotting in the IPython notebook, you will want to first run this *magic command* which configures the notebook to work well with plots:

# %matplotlib inline

# Now we can simply call the ``plot()`` method of any series or dataframe to get a reasonable view of the data:

import matplotlib.pyplot as plt
df['tripduration'].hist()

# ### Adjusting the Plot Style
#
# Matplotlib has a number of plot styles you can use. For example, if you like R you might use the ggplot style:

plt.style.use("ggplot")

# ### Other plot types
#
# Pandas supports a range of other plotting types; you can find these by using the <TAB> autocomplete on the ``plot`` method:

plt.

# For example, we can create a histogram of trip durations:



# If you'd like to adjust the x and y limits of the plot, you can use the ``set_xlim()`` and ``set_ylim()`` method of the resulting object:



# ## Breakout: Exploring the Data
#
# Make a plot of the total number of rides as a function of month of the year (You'll need to extract the month, use a ``groupby``, and find the appropriate aggregation to count the number in each group).



# Split this plot by gender. Do you see any seasonal ridership patterns by gender?



# Split this plot by user type. Do you see any seasonal ridership patterns by usertype?



# Repeat the above three steps, counting the number of rides by time of day rather that by month.



# Are there any other interesting insights you can discover in the data using these tools?



# ### Using Files
# - Writing and running python modules
# - Using python modules in your Jupyter Notebook

# A script for creating a dataframe with counts of the occurrence of a columns' values
df_count = df.groupby('from_station_id').count()
df_count1 = df_count[['trip_id']]
df_count2 = df_count1.rename(columns={'trip_id': 'count'})

df_count2.head()


def make_table_count(df_arg, groupby_column):
    df_count = df_arg.groupby(groupby_column).count()
    column_name = df.columns[0]
    df_count1 = df_count[[column_name]]
    df_count2 = df_count1.rename(columns={column_name: 'count'})
    return df_count2


dff = make_table_count(df, 'from_station_id')
dff.head()



StarcoderdataJupyterScriptsDedupFiltered