Section I: Cell Types

Exercise 1.1 : Code Cells and Interactive Execution

A Jupyter notebook, on the surface, is a sequence of cells.

  • Code cell: REP (read, evaluate, print) commands & output
  • Text cell: Markdown & Latex

By default, each cell in the notebook is akin to a terminal where python commands can be executed.

  • Enter : Next line,
  • Shift-Enter: Execute
  • Esc, A : Insert cell above
  • Esc, B : Insert cell below

In [2]:
print "Hello World!"


Hello World!

In [3]:
# Simple python comments indicated by "#"
# Think Twitter #smh

In [4]:
#Block of commands
x=3
y=4
x**y              # "**" is python's version of "^"


Out[4]:
81

In [5]:
#History stored via underscores, "_"=last executed command line, "__"=penultimate executed command line and so on.
_+19


Out[5]:
100

In [6]:
#To refer even further into the history, simply use "_" followed by the cell number
_4/9


Out[6]:
9

Magic functions & Help

At any juncture, typing any object followed by the "?" will bring up an information pager on the object.


In [7]:
import pandas as pd
pd.rolling_mean?

In [43]:
#information pager on iPython itself.
?

The "magic" functions are commands specific to iPython and provide a command-line interface. They're prefixed by % or %%.


In [44]:
%quickref

In [1]:
#%history

In [46]:
%time         # Outputs time for execution
range(10000); # the ";" supresses output to the screen


CPU times: user 6 µs, sys: 6 µs, total: 12 µs
Wall time: 21.9 µs

Exercise 1.2 : Markdown Cells

Keyboard Short : Esc, m Protocol: Markdown markup language (yes, the same one they use for Reddit comments)


In [ ]:

Equations in the notebook

Identical to the $\LaTeX{}$ math enviornment.

$f(n) = n^5 + 4n^2 + 2 |_{n=17}$

Exercise 1.3 : Dealing with cells

New cells: Insert tab (Menu bar, at the top of the page), or,

Keyboard Shorts: Esc, a (above); Esc, b (below)

Tab completion

The Tab key can be used to explore the structure of objects or just to finish commands, file names, addresses, etc.


In [9]:
pr       #hit tab for command completion

In [ ]:

Section II: Graphics

Exercise 2.1 : Plots & Figures in the notebook


In [40]:
%matplotlib inline

import matplotlib
import numpy as np
import matplotlib.pyplot as plt      # inline magic: Figures are embedded in the document.

In [42]:
#Data
x=np.linspace(0,2*np.pi,50)
y=np.sin(x)

#Plot
plt.plot(x,y,marker='o',color='blue')

#Plot Limits
plt.xlim(0,2*np.pi)

#Plot Title
plt.title("Sine Wave")

#Plot Labels
plt.xlabel('$ x $')
plt.ylabel('$ sin (x) $')


Out[42]:
<matplotlib.text.Text at 0x7f222b3c3390>

Basic MatPlotLib colors

  • b: blue
  • g: green
  • r: red
  • c: cyan
  • m: magenta
  • y: yellow
  • k: black
  • w: white

Basic MatPlotLib Marker symbols

marker description marker description marker description marker description
"." point "+" plus "," pixel "x" cross
"o" circle "D" diamond "d" thin_diamond
"8" octagon "s" square "p" pentagon "*" star
"|" vertical line "_" horizontal line "h" hexagon1 "H" hexagon2
0 tickleft 4 caretleft "<" triangle_left "3" tri_left
1 tickright 5 caretright ">" triangle_right "4" tri_right
2 tickup 6 caretup "^" triangle_up "2" tri_up
3 tickdown 7 caretdown "v" triangle_down "1" tri_down
"None" nothing None nothing " " nothing "" nothing

Exercise

Change the markers in the scatter plot to grey squares.


In [37]:
x=np.linspace(0,2*np.pi,10)
y=np.sin(x)
plt.scatter(x,y)


Out[37]:
<matplotlib.collections.PathCollection at 0x7f222b222f50>

Basic MatPlotLib Linestyles

linestyle description
'-' solid
'--' dashed
'-.' dashdot
':' dotted
'None' draw nothing
' ' draw nothing
'' draw nothing

Exercise

Change the linestyle in the plot below to dash-dot.


In [39]:
x=np.linspace(0,2*np.pi,50)
y=np.sin(x)
plt.plot(x,y,'-.')
plt.xlim(0,2*np.pi)
plt.title("Sine Wave")
plt.xlabel('$ x $')
plt.ylabel('$ sin (x) $')


Out[39]:
<matplotlib.text.Text at 0x7f222b0ac7d0>

Exercise

Use MatPlotLib to replicate the figure given below.


In [13]:
from IPython.core.display import Image, display
display(Image(filename='testimage.png'))



In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [4]:
x=np.linspace(0,2*np.pi,100)
plt.plot(x,np.sin(x),'-k',label="Sine")
plt.plot(x,np.cos(x),'--b',label="Cosine")
plt.xlim(0,2*np.pi)
plt.ylim(-1.1,1.1)
plt.legend()
plt.grid()


To learn more:

For specific plotting questions, its in you best interests to utilize the Matplotlib gallery You can look through the gallery, find a figure that has pieces of what you want, just click on it to see the code that generated it.


In [ ]:

Section III: Interactive Widgets

Interactive widgets enable a two-way communication between the user interface (in the browser) and the python kernel (in the backend). The base widgets class facilitates the development of widgets in the backend that can be rendered in the browser.


In [16]:
from IPython.html.widgets import interact
from IPython.html import widgets


/home/aashwin/anaconda2/lib/python2.7/site-packages/IPython/html.py:14: ShimWarning: The `IPython.html` package has been deprecated. You should import from `notebook` instead. `IPython.html.widgets` has moved to `ipywidgets`.
  "`IPython.html.widgets` has moved to `ipywidgets`.", ShimWarning)

First of all, we start off by defining a simple function, $f(x)=x^3$.


In [17]:
def f(x):
    print(x**3)

The interact function creates user interface controls for our function argument ($x$), and then calls the function, $f(x)=x^3$, with those arguments when the value of $x$ is changed by the user.

As an illustration, we'll pass our function object with the keyword argument*, $x=2$.

*Not positional! (R users beware)


In [ ]:
interact(f, x=2);

Stuff to note in the widget:

  • The default value of the slider is the value passed by the user (say $X$).
  • The range of the slider is $x \in [-X, 3X]$.

Controlling the widget slider:

  • How can I change the range of the slider?
  • I need the slider to be more/less responsive!!

IntSliderWidget(min=a, max=b, step=c, value=d)

Widget Exercise

Define a function to return the square root of a number, $g(x)=\sqrt(x)$ Construct and interactive widget using this function, so that the number is not negative(!!!) and the widget increments at $0.1$.


In [ ]:
#define the function here

In [ ]:
#call the interact function here

Bonus Exercise (if you are conversant in python)

What if I want a set of discrete values? Pass $x$ to interact as a dictionary.


In [ ]:
interact(f, x={'one':1,'two':2,'three':3,'four':4,'five':5});

In [ ]:
#call the interact function here to your function, g(x), with the values (1,4,9,16)

In [19]:
import pandas as pd
data = np.array([np.cumsum(np.random.random(1000) - 0.5)]).T
df = pd.DataFrame(data,columns=list('A'))
df.head(5)


Out[19]:
A
0 -0.207735
1 -0.133278
2 0.311785
3 0.340146
4 0.558346

In [20]:
smooth_df=pd.rolling_mean(df, 5)
smooth_df.head(10)


Out[20]:
A
0 NaN
1 NaN
2 NaN
3 NaN
4 0.173853
5 0.251899
6 0.327731
7 0.247435
8 0.204250
9 0.180348

In [21]:
plt.subplot(1,2,1)
plt.plot(df)
plt.title("Original Data")
plt.subplot(1,2,2)
plt.plot(smooth_df)
plt.title("Filtered Data")


Out[21]:
<matplotlib.text.Text at 0x7f56e2ab9150>

Interact Exercise I

define a python function that takes the width of the filter as an argument, applies the rolling mean to df and plots the filtered data


In [ ]:
#define the function here

Interact Exercise II

Pass this function object to the interact function with the range of the width as (1,50)


In [ ]:
# Call the interact function here

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]: