Jupyter Notebook for Beginners: A Tutorial
The Jupyter Notebook is an incredibly powerful tool for interactively developing and presenting data science projects. Although it is possible to use many different programming languages within Jupyter Notebooks, this article will focus on Python as it is the most common use case.
Behind every notebook runs a kernel. When you run a code cell, that code is executed within the kernel and any output is returned back to the cell to be displayed. The kernel's state persists over time and between cells — it pertains to the document as a whole and not individual cells.
For example, if you import libraries or declare variables in one cell, they will be available in another. In this way, you can think of a notebook document as being somewhat comparable to a script file, except that it is multimedia. Let's try this out to get a feel for it. First, we'll import a Python package and define a function.
Once we've executed the cell above, we can reference
square in any other cell.
This will work regardless of the order of the cells in your notebook. You can try it yourself, let's print out our variables again.
No surprises here! But now let's change
What do you think will happen if we run the cell containing our
Is 4 squared is 10?!
Most of the time, the flow in your notebook will be top-to-bottom, but it's common to go back to make changes. In this case, the order of execution stated to the left of each cell, such as
In , will let you know whether any of your cells have stale output. And if you ever wish to reset things, there are several incredibly useful options from the Kernel menu:
- Restart: restarts the kernel, thus clearing all the variables etc that were defined.
- Restart & Clear Output: same as above but will also wipe the output displayed below your code cells.
- Restart & Run All: same as above but will also run all your cells in order from first to last.
If your kernel is ever stuck on a computation and you wish to stop it, you can choose the Interupt option.
Choosing a kernal
You may have noticed that Jupyter gives you the option to change kernel, and in fact there are many different options to choose from. Back when you created a new notebook from the dashboard by selecting a Python version, you were actually choosing which kernel to use.
Not only are there kernels for different versions of Python, but also for over 100 languages including Java, C, and even Fortran. Data scientists may be particularly interested in the kernels for R and Julia, as well as both imatlab and the Calysto MATLAB Kernel for Matlab. The SoS kernel provides multi-language support within a single notebook. Each kernel has its own installation instructions, but will likely require you to run some commands on your computer.
Now we've looked at what a Jupyter Notebook is, it's time to look at how they're used in practice, which should give you a clearer understanding of why they are so popular. It's finally time to get started with that Fortune 500 data set mentioned earlier. Remember, our goal is to find out how the profits of the largest companies in the US changed historically.
It's worth noting that everyone will develop their own preferences and style, but the general principles still apply, and you can follow along with this section in your own notebook if you wish, which gives you the scope to play around.
Naming your notebooks
Before you start writing your project, you'll probably want to give it a meaningful name. Perhaps somewhat confusingly, you cannot name or rename your notebooks from the notebook app itself, but must use either the dashboard or your file browser to rename the
.ipynb file. We'll head back to the dashboard to rename the file you created earlier, which will have the default notebook file name
You cannot rename a notebook while it is running, so you've first got to shut it down. The easiest way to do this is to select "File > Close and Halt" from the notebook menu. However, you can also shutdown the kernel either by going to "Kernel > Shutdown" from within the notebook app or by selecting the notebook in the dashboard and clicking "Shutdown" (see image below).
You can then select your notebook and and click "Rename" in the dashboard controls.
Note that closing the notebook tab in your browser will not "close" your notebook in the way closing a document in a traditional application will. The notebook's kernel will continue to run in the background and needs to be shut down before it is truly "closed" — though this is pretty handy if you accidentally close your tab or browser! If the kernel is shut down, you can close the tab without worrying about whether it is still running or not.
Once you've named your notebook, open it back up and we'll get going.
It's common to start off with a code cell specifically for imports and setup, so that if you choose to add or change anything, you can simply edit and re-run the cell without causing any side-effects.
We import pandas to work with our data, Matplotlib to plot charts, and Seaborn to make our charts prettier. It's also common to import NumPy but in this case, although we use it via pandas, we don't need to explicitly. And that first line isn't a Python command, but uses something called a line magic to instruct Jupyter to capture Matplotlib plots and render them in the cell output; this is one of a range of advanced features that are out of the scope of this article.
Let's go ahead and load our data.
It's sensible to also do this in a single cell in case we need to reload it at any point.
Save and Checkpoint
Now we've got started, it's best practice to save regularly. Pressing
Ctrl + S will save your notebook by calling the "Save and Checkpoint" command, but what this checkpoint thing?
Every time you create a new notebook, a checkpoint file is created as well as your notebook file; it will be located within a hidden subdirectory of your save location called
.ipynb_checkpoints and is also a
.ipynb file. By default, Jupyter will autosave your notebook every 120 seconds to this checkpoint file without altering your primary notebook file. When you "Save and Checkpoint," both the notebook and checkpoint files are updated. Hence, the checkpoint enables you to recover your unsaved work in the event of an unexpected issue. You can revert to the checkpoint from the menu via "File > Revert to Checkpoint."
Investigating our data set
Now we're really rolling! Our notebook is safely saved and we've loaded our data set
df into the most-used pandas data structure, which is called a
DataFrame and basically looks like a table. What does ours look like?
|Year||Rank||Company||Revenue (in millions)||Profit (in millions)|
|Year||Rank||Company||Revenue (in millions)||Profit (in millions)|
|25495||2005||496||Wm. Wrigley Jr.||3648.6||493|
Looking good. We have the columns we need, and each row corresponds to a single company in a single year.
Let's just rename those columns so we can refer to them later.
Next, we need to explore our data set. Is it complete? Did pandas read it as expected? Are any values missing?
Okay, that looks good — that's 500 rows for every year from 1955 to 2005, inclusive.
Let's check whether our data set has been imported as we would expect. A simple check is to see if the data types (or dtypes) have been correctly interpreted.
Uh oh. It looks like there's something wrong with the profits column — we would expect it to be a
float64 like the revenue column. This indicates that it probably contains some non-integer values, so let's take a look.
|294||1955||295||Pacific Vegetable Oil||97.9||N.A.|
Just as we suspected! Some of the values are strings, which have been used to indicate missing data. Are there any other values that have crept in?
That makes it easy to interpret, but what should we do? Well, that depends how many values are missing.
It's a small fraction of our data set, though not completely inconsequential as it is still around 1.5%. If rows containing
N.A. are, roughly, uniformly distributed over the years, the easiest solution would just be to remove them. So let's have a quick look at the distribution.
At a glance, we can see that the most invalid values in a single year is fewer than 25, and as there are 500 data points per year, removing these values would account for less than 4% of the data for the worst years. Indeed, other than a surge around the 90s, most years have fewer than half the missing values of the peak. For our purposes, let's say this is acceptable and go ahead and remove these rows.
We should check that worked.
Great! We have finished our data set setup.
If you were going to present your notebook as a report, you could get rid of the investigatory cells we created, which are included here as a demonstration of the flow of working with notebooks, and merge relevant cells (see the Advanced Functionality section below for more on this) to create a single data set setup cell. This would mean that if we ever mess up our data set elsewhere, we can just rerun the setup cell to restore it.
Plotting with matplotlib
Next, we can get to addressing the question at hand by plotting the average profit by year. We might as well plot the revenue as well, so first we can define some variables and a method to reduce our code.
Now let's plot!
Wow, that looks like an exponential, but it's got some huge dips. They must correspond to the early 1990s recession and the dot-com bubble. It's pretty interesting to see that in the data. But how come profits recovered to even higher levels post each recession?
Maybe the revenues can tell us more.
That adds another side to the story. Revenues were no way nearly as badly hit, that's some great accounting work from the finance departments.
With a little help from Stack Overflow, we can superimpose these plots with +/- their standard deviations.
That's staggering, the standard deviations are huge. Some Fortune 500 companies make billions while others lose billions, and the risk has increased along with rising profits over the years. Perhaps some companies perform better than others; are the profits of the top 10% more or less volatile than the bottom 10%?
There are plenty of questions that we could look into next, and it's easy to see how the flow of working in a notebook matches one's own thought process, so now it's time to draw this example to a close. This flow helped us to easily investigate our data set in one place without context switching between applications, and our work is immediately sharable and reproducible. If we wished to create a more concise report for a particular audience, we could quickly refactor our work by merging cells and removing intermediary code.
Sharing your notebooks
When people talk of sharing their notebooks, there are generally two paradigms they may be considering. Most often, individuals share the end-result of their work, much like this article itself, which means sharing non-interactive, pre-rendered versions of their notebooks; however, it is also possible to collaborate on notebooks with the aid version control systems such as Git.
Before you share
A shared notebook will appear exactly in the state it was in when you export or save it, including the output of any code cells. Therefore, to ensure that your notebook is share-ready, so to speak, there are a few steps you should take before sharing:
- Click "Cell > All Output > Clear"
- Click "Kernel > Restart & Run All"
- Wait for your code cells to finish executing and check they did so as expected
This will ensure your notebooks don't contain intermediary output, have a stale state, and executed in order at the time of sharing.
Exporting your notebooks
Jupyter has built-in support for exporting to HTML and PDF as well as several other formats, which you can find from the menu under "File > Download As." If you wish to share your notebooks with a small private group, this functionality may well be all you need. Indeed, as many researchers in academic institutions are given some public or internal webspace, and because you can export a notebook to an HTML file, Jupyter Notebooks can be an especially convenient way for them to share their results with their peers.
But if sharing exported files doesn't cut it for you, there are also some immensely popular methods of sharing
.ipynb files more directly on the web.
With the number of public notebooks on GitHub exceeding 1.8 million by early 2018, it is surely the most popular independent platform for sharing Jupyter projects with the world. GitHub has integrated support for rendering
.ipynb files directly both in repositories and gists on its website. If you aren't already aware, GitHub is a code hosting platform for version control and collaboration for repositories created with Git. You'll need an account to use their services, but standard accounts are free.
Once you have a GitHub account, the easiest way to share a notebook on GitHub doesn't actually require Git at all. Since 2008, GitHub has provided its Gist service for hosting and sharing code snippets, which each get their own repository. To share a notebook using Gists:
- Sign in and browse to gist.github.com.
- Open your
.ipynbfile in a text editor, select all and copy the JSON inside.
- Paste the notebook JSON into the gist.
- Give your Gist a filename, remembering to add
.iypnbor this will not work.
- Click either "Create secret gist" or "Create public gist."
This should look something like the following:
If you created a public Gist, you will now be able to share its URL with anyone, and others will be able to fork and clone your work.
Creating your own Git repository and sharing this on GitHub is beyond the scope of this tutorial, but GitHub provides plenty of guides for you to get started on your own.
An extra tip for those using git is to add an exception to your
.gitignore for those hidden
.ipynb_checkpoints directories Jupyter creates, so as not to commit checkpoint files unnecessarily to your repo.
Having grown to render hundreds of thousands of notebooks every week by 2015, NBViewer is the most popular notebook renderer on the web. If you already have somewhere to host your Jupyter Notebooks online, be it GitHub or elsewhere, NBViewer will render your notebook and provide a shareable URL along with it. Provided as a free service as part of Project Jupyter, it is available at nbviewer.jupyter.org.
Initially developed before GitHub's Jupyter Notebook integration, NBViewer allows anyone to enter a URL, Gist ID, or GitHub username/repo/file and it will render the notebook as a webpage. A Gist's ID is the unique number at the end of its URL; for example, the string of characters after the last backslash in
https://gist.github.com/username/50896401c23e0bf417e89cd57e89e1de. If you enter a GitHub username or username/repo, you will see a minimal file browser that lets you explore a user's repos and their contents.
The URL NBViewer displays when displaying a notebook is a constant based on the URL of the notebook it is rendering, so you can share this with anyone and it will work as long as the original files remain online — NBViewer doesn't cache files for very long.
Starting with the basics, we have come to grips with the natural workflow of Jupyter Notebooks, delved into IPython's more advanced features, and finally learned how to share our work with friends, colleagues, and the world. And we accomplished all this from a notebook itself!
It should be clear how notebooks promote a productive working experience by reducing context switching and emulating a natural development of thoughts during a project. The power of Jupyter Notebooks should also be evident, and we covered plenty of leads to get you started exploring more advanced features in your own projects.
If you'd like further inspiration for your own Notebooks, Jupyter has put together a gallery of interesting Jupyter Notebooks that you may find helpful and the Nbviewer homepage links to some really fancy examples of quality notebooks. Also check out our list of Jupyter Notebook tips.
Want to learn more about Jupyter Notebooks? We have a guided project you may be interested in.
Bio: Benjamin Pryke is a Python and web developer with a background in computer science and machine learning. Co-founder of FinTech firm Machina Capital. Part-time gymnast and digital bohemian.
Original. Reposted with permission.
- Top 5 Best Jupyter Notebook Extensions
- 5 Things to Know About Machine Learning
- Fast.ai Lesson 1 on Google Colab (Free GPU)