Jupyter Notebooks Advanced Tutorial
Jupyter Notebooks Advanced Tutorial
2 JANUARY 2019
Advanced Jupyter
Notebooks: A Tutorial
order
Dataquest Dataexecution
Science Blog has the power to faze, and when it comesShare
to running
this
notebooks inside notebooks, things can get complicated fast.
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 2/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
Shell Commands
Dataquest Data Science Blog Share this
Every user will benefit at least from time-to-time from the ability to
interact directly with the operating system from within their
notebook. Any line in a code cell that you begin with an exclamation
mark will be executed as a shell command. This can be useful when
dealing with datasets or other files, and managing your Python
packages. As a simple illustration:
Hello World!
pandas==0.23.4
This is nifty
However,
Dataquest IPython
Data Science Blog magics offer a solution. Share this
Basic Magics
Magics are handy commands built into the IPython kernel that make
it easier to perform particular tasks. Although they often resemble
unix commands, under the hood they are all implemented in Python.
There exist far more magics than it would make sense to cover here,
but it's worth highlighting a variety of examples. We will start with a
few basics before moving on to more interesting cases.
There are two categories of magic: line magics and cell magics.
Respectively, they act on a single line or can be spread across
multiple lines or entire cells. To see the available magics, you can do
the following:
%lsmagic
As you can see, there are loads! Most are listed in the official
documentation, which is intended as a reference but can be
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 4/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
somewhat
Dataquest obtuse
Data Science Blog in places. Line magics start with a percent
Share this
It's worth noting that ! is really just a fancy magic syntax for shell
commands, and as you may have noticed IPython provides magics in
place of those shell commands that alter the state of the shell and are
thus lost by ! . Examples include %cd , %alias and %env .
Autosaving
First up, the %autosave magic let's you change how often your
notebook will autosave to its checkpoint file.
%autosave 60
%matplotlib inline
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 5/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
Debugging
The more experienced reader may have had concerns over the
ultimate efficacy of Jupyter Notebooks without access to a debugger.
But fear not! The IPython kernel has its own interface to the Python
debugger, pdb, and several options for debugging with it in your
notebooks. Executing the %pdb line magic will toggle on/off the
automatic triggering of pdb on error across all cells in your
notebook.
%pdb
raise NotImplementedError()
NotImplementedError:
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 6/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
> <ipython-input-31-022320062e1f>(2)<module>()
Dataquest Data Science Blog Share this
1 get_ipython().run_line_magic('pdb', '')
----> 2 raise NotImplementedError()
This exposes an interactive mode in which you can use the pdb
commands.
Timing Execution
Sometimes in research, it is important to provide runtime
comparisons for competing approaches. IPython provides the two
timing magics %time and %timeit , which each has both line and cell
modes. The former simply times either the execution of a single
statement or cell, depending on whether it is used in line or cell
mode.
n = 1000000
%time sum(range(n))
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 7/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
499999500000
%%time
total = 0
for i in range(n):
total += i
%timeit sum(range(n))
34.9 ms ± 276 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 8/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
Executing Different
In the output of
%lsmagic above, you mayLanguages
Dataquest Data Science Blog
have noticed a number of
Share this
%%HTML
This is <em>really</em> neat!
%%latex
Some important equations:
$$E = mc^2$$
$$e^{i \pi} = -1$$
2
E = mc
iπ
e = −1
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 9/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
Configuring Logging
Dataquest Data Science Blog Share this
Did you know that Jupyter has a built-in way to prominently display
custom error messages above cell output? This can be handy for
ensuring that errors and warnings about things like invalid inputs or
parameterisations are hard to miss for anyone who might be using
your notebooks. An easy, customisable way to hook into this is via
the standard Python logging module.
(Note: Just for this section, we'll use some screenshots so that we
can see how these errors look in a real notebook.)
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 10/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
This
Dataquest means
Data Sciencewe
Blogcan configure logging to display other kinds
Shareof
this
messages over stderr too.
Note that every time you run a cell that adds a new stream handler
via logger.addHandler(handler) , you will receive an additional line of
output each time for each message logged. We could place all the
logging config in its own cell near the top of our notebook and leave
it be or, as we have done here, brute force replace all existing
handlers on the logger. We had to do that in this case anyway to
remove the default handler.
It's also easy to log to an external file, which might come in handy if
you're executing your notebooks from the command line as
discussed later. Just use a FileHandler instead of a StreamHandler :
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 11/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
Extensions
As it is an open source webapp, plenty of extensions have been
developed for Jupyter Notebooks, and there is a long official list.
Indeed, in the Working with Databases section below we use the
ipython-sql extension. Another of particular note is the bundle of
extensions from Jupyter-contrib, which contains individual
extensions for spell check, code folding and much more.
You can install and set this up from the command line like so:
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 12/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
Note
Dataquest that
Data Jupyter-contrib
Science Blog only works in regular Jupyter Notebooks,
Share this
but there are new extensions for JupyterLab now being released on
GitHub.
Let's check out an example. First, we'll import our libraries and load
some data.
data = sns.load_dataset("tips")
data.head()
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 13/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
plt.scatter(data.total_bill, data.tip);
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 14/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
sns.set(style="darkgrid")
plt.scatter(data.total_bill, data.tip);
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 15/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
What an improvement, and from only one import and a single extra
line! Here, we used the darkgrid style, but Seaborn has a total of five
built-in styles for you to play with: darkgrid, whitegrid, dark, white,
and ticks.
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 16/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
Now we get default axis labels and an improved default marker for
each data point. Seaborn can also automatically group by categories
within your data to add another dimension to your plots. Let's
change the colour of our markers based on whether the group paying
the bill were smokers or not.
That's pretty neat! In fact, we can take this much further, but there's
simply too much detail to go into here. As a taster though, let's
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 17/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
colour
Dataquest by theBlog
Data Science size of the party paying the bill while also Share this
discriminating between smokers and non-smokers.
For more ways Seaborn allows you to visualise the structure of your
data and the statistical relationships within it, check out their
examples.
Macros
Like many users, you probably find yourself writing the same few
tasks over and over again. Maybe there's a bunch of packages you
always need to import when starting a new notebook, a few statistics
that you find yourself computing for every single dataset, or some
standard charts that you've produced countless times?
Jupyter lets you save code snippets as executable macros for use
across all your notebooks. Although executing unknown code isn't
necessarily going to be useful for anyone else trying to read or use
your notebooks, it's definitely a handy productivity boost while
you're prototyping, investigating, or just playing around.
Macros are just code, so they can contain variables that will have to
be defined before execution. Let's define one to use.
name = 'Tim'
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 19/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
Hello, Tim!
%macro -q __hello_world 23
%store __hello_world
The %macro magic takes a name and a cell number (the number in
the square brackets to the left of the cell; in this case 23 as in In
[23] ), and we've also passed -q to make it less verbose. %store
actually allows us to save any variable for use in other sessions; here,
we pass the name of the macro we created so we can use it again
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 20/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
after
Dataquest the
Data kernel
Science Blogis shut down or in other notebooks. Run without
Share this any
parameters, %store lists your saved items.
To load the macro from the store, we just run:
%store -r __hello_world
And to execute it, we merely need to run a cell that solely contains
the macro name.
__hello_world
Hello, Tim!
name = 'Ben'
When we run the macro now, our modified value is picked up.
__hello_world
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 21/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
DataquestHello,
Data Science
Ben!Blog Share this
This works because macros just execute the saved code in the scope
of the cell; if name was undefined we'd get an error.
But macros are far from the only way to share code across
notebooks.
Tasks such as importing the same set of packages over and over for
every project project are a perfect candidate for the %load magic,
which will load an external script into the cell in which it's executed.
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 22/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
We can load this simply by writing a one-line code cell, like so:
%load imports.py
Executing this will replace the cell contents with the loaded file.
# %load imports.py
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
Now we can run the cell again to import all our modules and we're
ready to go.
The %run magic is similar, except it will execute the code and display
any output, including Matplotlib plots. You can even execute entire
notebooks this way, but remember that not all code truly belongs in
a notebook. Let's check out an example of this magic; consider a file
containing the following short script.
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 23/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
Dataquestimport numpy as np
Data Science Blog Share this
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="darkgrid")
if __name__ == '__main__':
h = plt.hist(np.random.triangular(0, 5, 9, 1000), bins=100, linewidth
plt.show()
%run triangle_hist.py
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 24/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
<matplotlib.figure.Figure at 0x2ace50fe860>
Scripted Execution
Although the foremost power of Jupyter Notebooks emanates from
their interactive flow, it is also possible to run notebooks in a non-
interactive mode. Executing notebooks from scripts or the command
line provides a powerful way to produce automated reports or
similar documents.
Jupyter offers a command line tool that can be used, in its simplest
form, for file conversion and execution. As you are probably aware,
notebooks can be converted to a number of formats, available from
the UI under "File > Download As", including HTML, PDF, Python
script, and even LaTeX. This functionality is exposed on the
command line through an API called nbconvert . It is also possible to
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 25/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
execute
Dataquest notebooks
Data Science Blog within Python scripts, but this is already well
Share this
documented
It's importantand the examples
to stress, below
similarly should
to %run bewhile
, that equally
theapplicable.
ability to
execute notebooks standalone makes it possible to write all manor of
projects entirely within Jupyter notebooks, this is no substitute for
breaking up code into standard Python modules and scripts as
appropriate.
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 26/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
A common snag arises from the fact that any error encountered
running your notebook will halt execution. Fortunately, you can
throw in the --allow-errors flag to instruct nbconvert to output the
error message into the cell output instead.
In such cases, it's quite likely you may wish to parameterise your
notebooks in order to run them with different initial values. The
simplest way to achieve this is using environment variables, which
you define before executing the notebook.
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 27/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
lineData
Dataquest magic makes
Science Blog it easy to assign the value of an environment
Share this
import datetime as dt
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 28/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
On Windows
If you'd like to set your environment variables and run your
notebook in a single line on Windows, it isn't quite as simple:
cmd /C "set A_STRING=Hello, Tim!&& set AN_INT=42 && set A_FLOAT=3.14 && s
Keen readers will notice the lack of a space after defining A_STRING
and A_DATE above. This is because trailing spaces are significant to
the Windows set command, so while Python will successfully parse
the integer and the float by first stripping whitespace, we have to be
more careful with our strings.
Papermill injects a new cell into your notebook that instantiates the
parameters you pass in, parsing numeric inputs for you. This means
you can just use the variables without any extra set-up (though dates
still need to be parsed). Optionally, you can create a cell in your
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 29/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
notebook
Dataquest that
Data Science defines
Blog your default parameter values by clicking
Share this
"View > Cell Toolbar > Tags" and adding a "parameters" tag to the
cell of your choice.
Our brief glance so far uncovers only the tip of the Papermill iceberg.
The library can also execute and collect metrics across notebooks,
summarise collections of notebooks, and it provides an API for
storing data and Matplotlib plots for access in other scripts or
notebooks. It's all well documented in the GitHub readme, so there's
no need to reiterate here.
write
Dataquest Datashell orBlog
Science Python scripts that can batch produce multiple
Share this
Styling Notebooks
If you're looking for a particular look-and-feel in your notebooks,
you can create an external CSS file and load it with Python.
%%html
<style>
.css-example { color: darkcyan; }
</style>
%%html
<span class='css-example'>This text has a nice colour</span>
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 31/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
Using
Dataquest DataHTML cells
Science Blog would be fine for one or two lines, but it will
Share this
If you would rather customise all your notebooks at once, you can
write CSS straight into the ~/.jupyter/custom/custom.css file in your
Jupyter config directory instead, though this will only work when
running or converting notebooks on your own computer.
Hiding Cells
Although it's bad practice to hide parts of your notebook that would
aid other people's understanding, some of your cells may not be
important to the reader. For example, you might wish to hide a cell
that adds CSS styling to your notebook or, if you wanted to hide your
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 32/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
default
Dataquest and injected
Data Science Blog Papermill parameters, you could modify
Share your
this
%load_ext sql
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 33/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
%sql sqlite://
'Connected: @None'
dialect+driver://username:password@host:port/database
Note that if you leave the connection string empty, the extension will
try to use the DATABASE_URL environment variable; read more about
how to customise this in the Scripted Execution section above.
Next, let's quickly populate our database from the tips dataset from
Seaborn we used earlier.
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 34/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
tips = sns.load_dataset("tips")
%sql PERSIST tips
* sqlite://
'Persisted tips'
We can now execute queries on our database. Note that we can use a
multiline cell magic %% for multiline SQL.
%%sql
SELECT *
FROM tips
LIMIT 3
* sqlite://
Done.
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 35/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
YouData
Dataquest can parameterise
Science Blog your queries using locally scoped variables
Share this by
meal_time = 'Dinner'
%sql SELECT * FROM tips WHERE time = :meal_time LIMIT 3
* sqlite://
Done.
result = %sql SELECT * FROM tips WHERE total_bill > (SELECT AVG(tot
larger_bills = result.DataFrame()
larger_bills.head(3)
* sqlite://
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 36/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
Done.
Dataquest Data Science Blog Share this
And as you can see, converting to a pandas DataFrame was easy too,
which makes plotting results from our queries a piece of cake. Let's
check out some 95% confidence intervals.
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 37/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
Wrapping Up
From the start of the tutorial for beginners through to here, we've
covered a wide range of topics and really laid the foundations for
what it takes to become a Jupyter master. These articles aim serve as
a demonstration of the breadth of use-cases for Jupyter Notebooks
and how to use them effectively. Hopefully, you have gained a few
insights for your own projects!
Benjamin Pryke
Python and web developer with a background in computer science and Read More
machine learning Co founder of FinTech firm Machina Capital Part time
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 38/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
machine learning. Co-founder of FinTech firm Machina Capital. Part-time
Dataquest gymnast
Data Science
andBlog
digital bohemian. Share this
CAREER
Dec 27, 2018
Jan 03, 2019
9 Reasons Excel Users
How to Write a Great Data Should Consider Learning
Science Resume Programming
What are data science recruiters looking Microsoft Excel could be the single most
for in a resume? Here's the scoop on popular piece of software in the business
community. Released over thirty years
how to write a data science resume or ago, Excel is still used every day in
CV that will get you hired. countries across the globe to store,
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 39/40
3/2/2019 Jupyter Notebooks Advanced Tutorial
https://www.dataquest.io/blog/advanced-jupyter-notebooks-tutorial/ 40/40