Search
Jupyter Notebook Guide
  • Interactive computing, all in the browser
  • A notebook consists of markup, code and results

Notebook Screen

The Jupyter Notebook is a tool for interactive computing. It provides a web interface so you can code, write, compute, and analyze, all in the browser. The notebook thus generated can be structured to include markup (descriptions), code (algorithm), and results of the computuation (data and analytics).

While Jupyter Notebook supports different languages, our focus is on Python 3.

Interface

  • Click the New button, then Python 3 to create a notebook
  • Once in the notebook, click on the name (Untitled by default) to rename it

Interface

Cell

  • Notebook: a sequence of cells
  • Major types of cells:
    1. Code Cell
    2. Markdown Cell

The basic element of a notebook is a cell. Notebook is essentially a number of cells arranged in a particular ordered. There are two major types of cells: the code cell where you can program and execute, and the markdown cell where you write and structure your report content.

Operations:

  • Menu bar to insert, run, merge, delete cells, etc.
  • Toolbar has buttons for quick access to related menu items
  • Most efficient is Keyboard Shortcut, for example:
    • Shift, Enter or Ctrl, Enter (two keys) to run the current cell
    • Shift, Ctrl, - (minus) (three keys) to split a cell at the cursor
    • Shift, M to merge selected cells
    • A to insert a new cell above
    • B to insert a new cell below

To find out about more shortcuts:

  1. Go to menu Help > Keyboard Shortcuts, or
  2. Simply press H (in the command mode).

Two Modes

You can switch between two modes:

  • Hit Enter to enter Edit mode
  • Press Esc to enter the Command mode Mode

Working with keyboard shortcuts, it is important to differentiate the two modes.

Most of the shortcuts works in the Command mode. For example,

In Command mode, press:

  • M to change the cell to Markdown;
  • Y to change the cell to Code.

What happen if you press M and Y in the Edit mode? You simply type M and Y into the cell. So if you typing in the cell and want to change the type, first press Esc to enter the command mode, and then hit M or Y to make the change.

Code Cell

A code cell is where:

  • You develop Python code
  • Everything should be in the Python syntax

A code cell can be run:

  • Using a kernel in the back:
  • Output will be shown after the cell
    1. Text output, e.g. from a print statement
    2. HTML output, e.g. a HTML table from the pandas package
    3. Visualization and figures, e.g. from matplotlib

For example, press Shift, Enter in the following code cell on a notebook:

print("Hello, world!")
Hello, world!

It will produce the text output Hello, world!

%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([[0,0],[1,1]], "b--", linewidth=3, label="line")
plt.show()

It will run the code and produce the figure that follows.

Markdown Cell

A markdown cell is where you:

  • Write: in a rich text format
  • The Markdown language: simple and powerful
  • Can combine with other markups such as HTML and LaTeX.

For example, the following in the markdown cell:

markdown
##### Heading Level 5
I am writing in **Markdown**, in <span style="color:red;">HTML</span>, and LaTeX $\sqrt{\frac{3}{5}}$.

will render:

Heading Level 5

I am writing in Markdown, in HTML, and in LaTeX math $\sqrt{\frac{3}{5}}$.

Markdown Quick References

Headers

markdown
# H1
## H2
### H3
#### H4
##### H5
###### H6

Ordered Lists

markdown
1. First item
2. Second item
3. Third item

Unordered Lists

markdown
+ Apple
+ Orange
+ Banana

Embedded Lists

markdown
+ John's TODO: 
  1. Buy parts
  2. Fix car
  3. Clean garage
+ Groceries
  - Flour
  - Vegetables
  - Fruit
markdown
[Search Engine](https://www.google.com)

Images

markdown
![My Photo](images/photo.jpg)

Code (verbatim)

print("Showing the code only!")
document.write("Hello again!");

Tables

markdown
|            | attribute 1 | attribute 2 | .. | attribute k |
|------------|-------------|-------------|----|-------------|
| object 1   |             |             |    |             |
| object 2   |             |             |    |             |
| ..         |             |             |    |             |

Blockquotes

markdown
Einstein: 
> God does not play dice.

Horizontal Lines (Rules)

markdown
---
___
***

HTML

For more sophisticated formats, you can include HTML to, for example:

  • Change the size and style of an image;
  • Write text in different colors and fonts;

You may consult the following:

LaTeX

Here is an example of LaTeX (MathJax subset):

Notebook Magics

Magic

Magics are mechanisms to make it easier to perform certain tasks.

Try the following in a code cell:

%lsmagic
Available line magics:
%alias  %alias_magic  %autoawait  %autocall  %automagic  %autosave  %bookmark  %cat  %cd  %clear  %colors  %conda  %config  %connect_info  %cp  %debug  %dhist  %dirs  %doctest_mode  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %lf  %lk  %ll  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %lx  %macro  %magic  %man  %matplotlib  %mkdir  %more  %mv  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %pip  %popd  %pprint  %precision  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %rep  %rerun  %reset  %reset_selective  %rm  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode

Available cell magics:
%%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile

Automagic is ON, % prefix IS NOT needed for line magics.

It shows all available magics in your Jupyter environment. There are two types of magics:

  • Line magic, with %, works on a single line of code;
  • Cell magic, with %%, applies to the entire cell;

Timing

If you want to know how fast a piece of code performs, you may use:

  • %time: runs the code once and reports the time;
  • %timeit: runs the code multiple times and reports the average time.

For example:

n = 10**6
sum(range(n))
499999500000

The above code computes the sum of integers $1,2,..,10^6-1$. To time the computation:

%time sum(range(n))
CPU times: user 16.6 ms, sys: 248 µs, total: 16.9 ms
Wall time: 18.3 ms
499999500000

Or you can time the whole cell:

%%time
n = 10**6
sum(range(n))
CPU times: user 18.6 ms, sys: 128 µs, total: 18.7 ms
Wall time: 18.7 ms
499999500000

Matplotlib Display

Earlier, we used %matplotlib inline to generate a figure in the notebook. There are additionl options one can use with the %matplotlib magic.

For example:

%matplotlib notebook
import matplotlib.pyplot as plt
plt.plot([[0,0],[1,1]], "b--", linewidth=3, label="line")
plt.show()

This produces an interactive figure that you can zoom and resize.

There are many other magics such as those for debugging, logging, and automatic actions on the notebook. And I encourage you to explore on your own.

Summary

to organize

Jupyter Notebook is a simple yet very powerful tool. I hope it helps you better organize your data, code, and analysis.