We will start today with the interactive environment that we will be using often through the course: the IPython/Jupyter Notebook.
We will walk through the following steps together:
Download miniconda (be sure to get Version 3.5) and install it on your system (hopefully you have done this before coming to class)
Use the conda
command-line tool to update your package listing and install the IPython notebook:
Update conda
's listing of packages for your system:
$ conda update conda
Install IPython notebook and all its requirements
$ conda install ipython-notebook
Navigate to the directory containing the course material. For example:
$ cd ~/courses/CSE599/
You should see a number of files in the directory, including these:
$ ls
...
Breakout-Simple-Math.ipynb
CSE599_Lecture_2.ipynb
...
Type ipython notebook
in the terminal to start the notebook
$ ipython notebook
If everything has worked correctly, it should automatically launch your default browser
Click on CSE599_Lecture_2.ipynb
to open the notebook containing the content for this lecture.
With that, you're set up to use the IPython notebook!
Now that we have the IPython notebook up and running, we're going to do a short breakout exploring some of the mathematical functionality that Python offers.
Please open Breakout-Simple-Math.ipynb, find a partner, and make your way through that notebook, typing and executing code along the way.
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
: Numerical PythonNumpy 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
: Scientific PythonScipy 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
: Labeled Data Manipulation in PythonPandas 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 statistical language (and in particular the so-called "Hadley Stack"), much of the functionality in Pandas should feel very familiar.
matplotlib
: Visualization in PythonMatplotlib 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).
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.
In [1]:
import numpy
numpy.__path__
Out[1]:
In [2]:
import pandas
In [5]:
df = pandas.DataFrame()
Because we'll use it so much, we often import under a shortened name using the import ... as ...
pattern:
In [6]:
import pandas as pd
In [7]:
df = pd.DataFrame()
Now we can use the read_csv
command to read the comma-separated-value data:
In [8]:
data = pd.read_csv('2015_trip_data.csv')
Note: strings in Python can be defined either with double quotes or single quotes
The head()
and tail()
methods show us the first and last rows of the data
In [10]:
data.head()
Out[10]:
In [11]:
data.tail()
Out[11]:
The shape
attribute shows us the number of elements:
In [12]:
data.shape
Out[12]:
The columns
attribute gives us the column names
In [13]:
data.columns
Out[13]:
The index
attribute gives us the index names
In [14]:
data.index
Out[14]:
The dtypes
attribute gives the data types of each column:
In [15]:
data.dtypes
Out[15]:
Access columns by name using square-bracket indexing:
In [17]:
data["trip_id"]
Out[17]:
Mathematical operations on columns happen element-wise:
In [18]:
data['tripduration'] / 60
Out[18]:
Columns can be created (or overwritten) with the assignment operator. Let's create a tripminutes column with the number of minutes for each trip
In [19]:
data['tripminutes'] = data['tripduration'] / 60
In [20]:
data.head()
Out[20]:
One trick to know when working with columns of times is that Pandas DateTimeIndex
provides a nice interface for working with columns of times:
In [21]:
times = pd.DatetimeIndex(data['starttime'])
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:
In [23]:
times
Out[23]:
In [24]:
times.dayofweek
Out[24]:
In [25]:
times.month
Out[25]:
Note: math functionality can be applied to columns using the NumPy package: for example:
In [26]:
import numpy as np
np.exp(data['tripminutes'])
Out[26]:
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:
In [27]:
pd.value_counts(data['gender'])
Out[27]:
In [28]:
pd.value_counts(data['birthyear'])
Out[28]:
Or to break down rides by age:
In [29]:
pd.value_counts(data['birthyear']).sort_index()
Out[29]:
In [30]:
pd.value_counts(2015 - data['birthyear']).sort_index()
Out[30]:
What else might we break down rides by?
In [31]:
pd.value_counts(times.dayofweek)
Out[31]:
We can sort by the index rather than the counts if we wish:
In [ ]:
pd.value_counts(times.dayofweek, sort=False)
In [ ]:
pd.value_counts(times.month)
In [ ]:
pd.value_counts(times.month, sort=False)
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)
In [32]:
from IPython.display import Image
Image('split_apply_combine.png')
Out[32]:
Let's break take this in smaller steps. First, let's look at the data by hour across all days in the year.
In [33]:
pd.value_counts(times.hour)
Out[33]:
groupby allows us to look at the number of values for each column and each value.
In [34]:
data.groupby(times.hour).count()
Out[34]:
Now, let's find the average length of a ride as a function of time of day:
In [35]:
data.groupby(times.hour)['tripminutes'].mean()
Out[35]:
You can specify a groupby using the names of table columns and compute other functions, such as the mean.
In [36]:
data.groupby(['gender'])['tripminutes'].mean()
Out[36]:
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>()
You can even group by multiple values: for example we can look at the trip duration by time of day and by gender:
In [ ]:
grouped = data.groupby([times.hour, 'gender'])['tripminutes'].mean()
grouped
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:
In [ ]:
grouped.unstack()
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:
In [37]:
%matplotlib inline
Now we can simply call the plot()
method of any series or dataframe to get a reasonable view of the data:
In [38]:
data.groupby([times.hour, 'usertype'])['tripminutes'].mean().unstack().plot()
Out[38]:
The default formatting is not very nice; I often make use of the Seaborn library for better plotting defaults.
You should do this in bash
$ conda install seaborn
Then this in python
import seaborn
seaborn.set()
data.groupby([times.hour, 'usertype'])['tripminutes'].mean().unstack().plot()
In [39]:
data.plot.hist()
Out[39]:
For example, we can create a histogram of trip durations:
In [ ]:
data['tripminutes'].plot.hist(bins=100)
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:
In [ ]:
plot = data['tripminutes'].plot.hist(bins=500)
plot.set_xlim(0, 50)
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In the homework this week, you will have a chance to apply some of these patterns to a brand new (but closely related) dataset.