IPython Notebook


In [24]:
# This is a python execution cell.
# Anything you could do in a python shell or script, you can do here.

# To execute a cell, type CTRL-Enter.
# You can also type SHIFT-Enter to execute and move to the next cell,
# and you can type OPTION-Enter to execute and insert a new cell below.

def foo():
    print "IPython Notebook is Awesome!"

foo()

# The last expression in a cell is always displayed as the cell's output when
# it's executed.
[1,2,3,4]


IPython Notebook is Awesome!
Out[24]:
[1, 2, 3, 4]
IPython Notebook supports more than just Python cells. This is a raw text cell. Use it to insert unformatted text between cells.

This is a level 1 header cell.

This is a level 2 header cell.

This is a level 3 header cell.

This is a level 4 header cell.

This is a level 5 header cell.
This is a level 6 header cell.

This is a Markdown cell.

Markdown is a text-to-HTML conversion tool for web writers. Markdown allows you to write using an easy-to-read, easy-to-write plain text format, then convert it to structurally valid XHTML (or HTML).

  • Markdown supports bulleted lists.

    • You can nest lists as deep as you want.
      • List elements don't have to be text either.
    • Reasons to like Markdown:

      1. It also supports numbered lists.
      2. It has support for code() formatting.
      3. You can embed arbitrary HTML

        Such as,for example,
        a table.
      4. It even has support for code blocks:

         class  Monad m  where
             (>>=)            :: m a -> (a -> m b) -> m b
             (>>)             :: m a -> m b -> m b
             return           :: a -> m a
             fail             :: String -> m a
             m >> k           =  m >>= \_ -> k

Notebook Magics:

Most of the magics that work in the IPython shell also work in the notebook. Additionally, there are some magics that only work in the notebook.

Autocomplete and Inline Documentation

  • Pressing the TAB key part of the way through a variable name autocompletes that name.
  • Autocomplete also works on attributes (e.g. pandas.DataF<TAB> -> pandas.DataFrame).
  • You can bring up documentation for a function or class inline with SHIFT+TAB

Execute this cell before trying the autocomplete examples in the next cell.


In [25]:
import pandas
class Point(object):
    """
    A class-level docstring.
    """
    def __init__(self, x, y=3):
        """
        Constructor docstring. SHIFT+TAB will show you this first line.
        
        SHIFT + two TABs will show you the entire docstring.
        """
        self.x, self.y = x, y
        
long_variable_name = Point(3,4)

Try it out!


In [26]:
pan              # Pressing TAB here will autocomplete pandas.
pandas.           # Pressing TAB here will show you the top-level attributes of pandas.
pandas.D          # Pressing TAB here will show you DataFrame, DatetimeIndex, and DateOffset.
pandas.DataFrame # Pressing TAB here will show you methods and attributes of DataFrame.

long_variable_name             # Pressing TAB here will autocomplete long_variable_name

                  # Hold SHIFT and press TAB with your cursor in 
x = Point(1,2)       # the parentheses to see info on how to make a Point object.

Documentation:

  • Typing <expression>? shows the function signature and documentation for that expression.
  • Typing <expression>?? takes you to the source code for the expression.
  • You can also use the pinfo and pinfo2 magics to get the same info.
  • Notebook Only: Press SHIFT+TAB while hovering over an object to open in-line documentation for that callable.

In [27]:
pandas.DataFrame?

In [29]:
pandas.DataFrame.plot??

In [ ]:
pandas.DataFrame.|plot

Cell Magics

In addition to all the magics we saw above, there are additional magics that operate at the cell level. Many of these are focused around interoperation with other languages.

Javascript


In [ ]:
%%javascript
alert('foo')

R

Some cell magics are provided by extensions. Here we load the rpy2's cell magic for interacting with R.


In [31]:
%load_ext rpy2.ipython


The rpy2.ipython extension is already loaded. To reload it, use:
  %reload_ext rpy2.ipython

In [32]:
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(10,5), columns=['A','B','C','D','E'])
df


Out[32]:
A B C D E
0 -0.289653 0.035397 0.269596 -0.123346 -0.226254
1 1.610621 -0.213442 0.646168 0.170514 1.779766
2 1.135251 -1.238080 0.576340 -0.603030 -0.595476
3 -0.819130 -1.518475 1.292778 1.065084 -1.714239
4 0.669536 -1.068135 -2.177952 0.287773 -0.768615
5 -0.182392 -0.012740 -0.427951 0.485842 1.201008
6 -0.543909 -0.123381 -0.130659 -0.614535 2.536462
7 0.658801 -0.033578 0.587168 -0.076015 0.998674
8 0.711228 -1.877669 -1.090271 -1.858527 0.112624
9 1.879868 0.527192 0.837595 -0.416209 1.090820

In [33]:
# Push our DataFrame into R.
%Rpush df

In [34]:
%%R
# Despite also being valid python, this is actually R code!
col_A = df['A']
plot(col_A)



In [35]:
# We can also pull values back out of R!
%Rpull col_A
col_A


Out[35]:
A
0 -0.289653
1 1.610621
2 1.135251
3 -0.819130
4 0.669536
5 -0.182392
6 -0.543909
7 0.658801
8 0.711228
9 1.879868

Builtin Rich Display Formats

IPython supports a wide array of rich display formats, including:

  • LaTeX
  • Markdown
  • HTML
  • SVG
  • PNG

...and more


In [36]:
import IPython.display
dir(IPython.display)[:18]


Out[36]:
['Audio',
 'DisplayObject',
 'FileLink',
 'FileLinks',
 'HTML',
 'IFrame',
 'Image',
 'JSON',
 'Javascript',
 'Latex',
 'Markdown',
 'Math',
 'Pretty',
 'SVG',
 'ScribdDocument',
 'TextDisplayObject',
 'VimeoVideo',
 'YouTubeVideo']

LaTeX


In [37]:
from IPython.display import Math
Math(r'w_A = \frac{\sigma_B - Cov(r_A, r_B)}{\sigma_B^2 + \sigma_A^2 - 2 Cov(r_A, r_B)}')


Out[37]:
$$w_A = \frac{\sigma_B - Cov(r_A, r_B)}{\sigma_B^2 + \sigma_A^2 - 2 Cov(r_A, r_B)}$$

HTML


In [38]:
from IPython.display import HTML
HTML('''\
To learn more about IPython's rich display capabilities, click
<a href="http://ipython.org/ipython-doc/dev/config/integrating.html">here</a>.
''')


Out[38]:
To learn more about IPython's rich display capabilities, click here.

YouTube Video


In [39]:
from IPython.display import YouTubeVideo
YouTubeVideo("https://www.youtube.com/watch?v=B_XiSozs-SE")


Out[39]:

Customizing Object Display

If a class implements one of many _repr_ methods, IPython will use that method to display the object.


In [ ]:
class Table(object):
    """
    A simple table represented as a list of lists.
    """

    def __init__(self, lists):
        self.lists = lists
        
    def make_row(self, l):
        columns = ''.join('<td>{value}</td>'.format(value=value) for value in l)
        return '<tr>{columns}</tr>'.format(columns=columns)
        
    def _repr_html_(self):
        rows = ''.join(self.make_row(l) for l in self.lists)
        return "<table>{rows}</table>".format(rows=rows)

In [ ]:
Table(
    [
        [1,2,3], 
        [4,5,6]
    ]
)