Subtopic A: What is a Jupyter Notebook and Why is it Useful?
Jupyter Notebooks are locally run web applications which contain live code, equations, figures, interactive apps, and Markdown text. The standard language is Python, and that's what we'll be using for this book; however, note that a variety of alternatives are supported. This includes the other dominant data science language, R:
Those familiar with R will know about R Markdown. Markdown documents allow for Markdown-formatted text to be combined with executable code. Markdown is a simple language used for styling text on the web. For example, most GitHub repositories have a README.md
Markdown file. This format is useful for basic text formatting. It's comparable to HTML but allows for much less customization. Commonly used symbols in Markdown include hashes (#
) to make text into a heading, square and round brackets to insert hyperlinks, and stars to create italicized or bold text:
Having seen the basics of Markdown, let's come back to R Markdown, where Markdown text can be written alongside executable code. Jupyter Notebooks offer the equivalent functionality for Python, although, as we'll see, they function quite differently than R Markdown documents. For example, R Markdown assumes you are writing Markdown unless otherwise specified, whereas Jupyter Notebooks assume you are inputting code. This makes it more appealing to use Jupyter Notebooks for rapid development and testing.
From a data science perspective, there are two primary types for a Jupyter Notebook depending on how they are used: lab-style and deliverable.
Lab-style Notebooks are meant to serve as the programming analog of research journals. These should contain all the work you've done to load, process, analyze, and model the data. The idea here is to document everything you've done for future reference, so it's usually not advisable to delete or alter previous lab-style Notebooks. It's also a good idea to accumulate multiple date-stamped versions of the Notebook as you progress through the analysis, in case you want to look back at previous states.
Deliverable Notebooks are intended to be presentable and should contain only select parts of the lab-style Notebooks. For example, this could be an interesting discovery to share with your colleagues, an in-depth report of your analysis for a manager, or a summary of the key findings for stakeholders.
In either case, an important concept is reproducibility. If you've been diligent in documenting your software versions, anyone receiving the reports will be able to rerun the Notebook and compute the same results as you did. In the scientific community, where reproducibility is becoming increasingly difficult, this is a breath of fresh air.
Subtopic C: Jupyter Features
Jupyter has many appealing features that make for efficient Python programming. These include an assortment of things, from methods for viewing docstrings to executing Bash commands. Let's explore some of these features together in this section.
Explore some of Jupyter's most useful features
- From the Jupyter Dashboard, navigate to the
lesson-1
directory and open the lesson-1-workbook.ipynb
file by selecting it. The standard file extension for Jupyter Notebooks is .ipynb
, which was introduced back when they were called IPython Notebooks. - Scroll down to
Subtopic C: Jupyter Features
in the Jupyter Notebook. We start by reviewing the basic keyboard shortcuts. These are especially helpful to avoid having to use the mouse so often, which will greatly speed up the workflow. Here are the most useful keyboard shortcuts. Learning to use these will greatly improve your experience with Jupyter Notebooks as well as your own efficiency:- Shift + Enter is used to run a cell
- The Esc key is used to leave a cell
- The M key is used to change a cell to Markdown (after pressing Esc)
- The Y key is used to change a cell to code (after pressing Esc)
- Arrow keys move cells (after pressing Esc)
- The Enter key is used to enter a cell
Moving on from shortcuts, the help option is useful for beginners and experienced coders alike. It can help provide guidance at each uncertain step.
Users can get help by adding a question mark to the end of any object and running the cell. Jupyter finds the docstring for that object and returns it in a pop-out window at the bottom of the app.
- Run the Getting Help section cells and check out how Jupyter displays the docstrings at the bottom of the Notebook. Add a cell in this section and get help on the object of your choice:
Tab completion can be used to do the following:
- List available modules when importing external libraries
- List available modules of imported external libraries
- Function and variable completion
This can be especially useful when you need to know the available input arguments for a module, when exploring a new library, to discover new modules, or simply to speed up workflow. They will save time writing out variable names or functions and reduce bugs from typos. The tab completion works so well that you may have difficulty coding Python in other editors after today!
- Click into an empty code cell in the Tab Completion section and try using tab completion in the ways suggested immediately above. For example, the first suggestion can be done by typing
import
(including the space after) and then pressing the Tab key: - Last but not least of the basic Jupyter Notebook features are magic commands. These consist of one or two percent signs followed by the command. Magics starting with
%%
will apply to the entire cell, and magics starting with %
will only apply to that line. This will make sense when seen in an example.Scroll to the Jupyter Magic Functions section and run the cells containing %lsmagic
and %matplotlib inline:
%lsmagic
lists the available options. We will discuss and show examples of some of the most useful ones. The most common magic command you will probably see is %matplotlib inline
, which allows matplotlib figures to be displayed in the Notebook without having to explicitly use plt.show()
.
The timing functions are very handy and come in two varieties: a standard timer (%time
or %%time
) and a timer that measures the average runtime of many iterations (%timeit
and %%timeit
).
- Run the cells in the Timers section. Note the difference between using one and two percent signs.
Even by using a Python kernel (as you are currently doing), other languages can be invoked using magic commands. The built-in options include JavaScript, R, Pearl, Ruby, and Bash. Bash is particularly useful, as you can use Unix commands to find out where you are currently (pwd
), what's in the directory (ls
), make new folders (mkdir
), and write file contents (cat
/ head
/ tail
).
- Run the first cell in the Using bash in the notebook section. This cell writes some text to a file in the working directory, prints the directory contents, prints an empty line, and then writes back the contents of the newly created file before removing it:
- Run the following cells containing only
ls
and pwd
. Note how we did not have to explicitly use the Bash magic command for these to work.There are plenty of external magic commands that can be installed. A popular one is ipython-sql
, which allows for SQL code to be executed in cells.
- If you've not already done so, install
ipython-sql
now. Open a new terminal window and execute the following code: - Run the
%load_ext sql
cell to load the external command into the Notebook:This allows for connections to remote databases so that queries can be executed (and thereby documented) right inside the Notebook.
- Run the cell containing the SQL sample query:
Here, we first connect to the local sqlite source; however, this line could instead point to a specific database on a local or remote server. Then, we execute a simple SELECT
to show how the cell has been converted to run SQL code instead of Python.
- Moving on to other useful magic functions, we'll briefly discuss one that helps with documentation. The command is
%version_information
, but it does not come as standard with Jupyter. Like the SQL one we just saw, it can be installed from the command line with pip
.If not already done, install the version documentation tool now from the terminal using pip
. Open up a new window and run the following code:
Once installed, it can then be imported into any Notebook using %load_ext version_information
. Finally, once loaded, it can be used to display the versions of each piece of software in the Notebook.
- Run the cell that loads and calls the
version_information
command:
Converting a Jupyter Notebook to a Python Script
You can convert a Jupyter Notebook to a Python script. This is equivalent to copying and pasting the contents of each code cell into a single .py
file. The Markdown sections are also included as comments.
The conversion can be done from the NotebookApp
or in the command line as follows:
This is useful, for example, when you want to determine the library requirements for a Notebook using a tool such as pipreqs
. This tool determines the libraries used in a project and exports them into a requirements.txt
file (and it can be installed by running pip install pipreqs
).
The command is called from outside the folder containing your .py
files. For example, if the .py
files are inside a folder called lesson-1
, you could do the following:
The resulting requirements.txt
file for lesson-1-workbook.ipynb
looks like this:
Subtopic D: Python Libraries
Having now seen all the basics of Jupyter Notebooks, and even some more advanced features, we'll shift our attention to the Python libraries we'll be using in this book. Libraries, in general, extend the default set of Python functions. Examples of commonly used standard libraries are datetime
, time
, and os
. These are called standard libraries because they come standard with every installation of Python.
For data science with Python, the most important libraries are external, which means they do not come standard with Python.
The external data science libraries we'll be using in this book are NumPy, Pandas, Seaborn, matplotlib, scikit-learn, Requests, and Bokeh. Let's briefly introduce each.
Note
It's a good idea to import libraries using industry standards, for example, import numpy as np;
this way, your code is more readable. Try to avoid doing things such as from numpy import *
, as you may unwittingly overwrite functions. Furthermore, it's often nice to have modules linked to the library via a dot (.
) for code readability.
- NumPy offers multi-dimensional data structures (arrays) on which operations can be performed far quicker than standard Python data structures (for example, lists). This is done in part by performing operations in the background using C. NumPy also offers various mathematical and data manipulation functions.
- Pandas is Python's answer to the R DataFrame. It stores data in 2D tabular structures where columns represent different variables and rows correspond to samples. Pandas provides many handy tools for data wrangling such as filling in NaN entries and computing statistical descriptions of the data. Working with Pandas DataFrames will be a big focus of this book.
- Matplotlib is a plotting tool inspired by the MATLAB platform. Those familiar with R can think of it as Python's version of ggplot. It's the most popular Python library for plotting figures and allows for a high level of customization.
- Seaborn works as an extension to matplotlib, where various plotting tools useful for data science are included. Generally speaking, this allows for analysis to be done much faster than if you were to create the same things manually with libraries such as matplotlib and scikit-learn.
- scikit-learn is the most commonly used machine learning library. It offers top-of-the-line algorithms and a very elegant API where models are instantiated and then fit with data. It also provides data processing modules and other tools useful for predictive analytics.
- Requests is the go-to library for making HTTP requests. It makes it straightforward to get HTML from web pages and interface with APIs. For parsing the HTML, many choose BeautifulSoup4, which we will also cover in this book.
- Bokeh is an interactive visualization library. It functions similar to matplotlib, but allows us to add hover, zoom, click, and use other interactive tools to our plots. It also allows us to render and play with the plots inside our Jupyter Notebook.
Having introduced these libraries, let's go back to our Notebook and load them, by running the import
statements. This will lead us into our first analysis, where we finally start working with a dataset.
Import the external libraries and set up the plotting environment
- Open up the
lesson 1
Jupyter Notebook and scroll to the Subtopic D: Python Libraries
section.Just like for regular Python scripts, libraries can be imported into the Notebook at any time. It's best practice to put the majority of the packages you use at the top of the file. Sometimes it makes sense to load things midway through the Notebook and that is completely OK.
- Run the cells to import the external libraries and set the plotting options:
For a nice Notebook setup, it's often useful to set various options along with the imports at the top. For example, the following can be run to change the figure appearance to something more aesthetically pleasing than the matplotlib and Seaborn defaults:
So far in this book, we've gone over the basics of using Jupyter Notebooks for data science. We started by exploring the platform and finding our way around the interface. Then, we discussed the most useful features, which include tab completion and magic functions. Finally, we introduced the Python libraries we'll be using in this book.
The next section will be very interactive as we perform our first analysis together using the Jupyter Notebook.