In [1]:
print "Hallo Welt!"
Hallo Welt!
In [2]:
2**200
Out[2]:
1606938044258990275541962092341162602522202993782792835301376L
In [3]:
# Multi-line editing. Syntax-coloring.
for num in ['eins', 'zwei', 'drei']:
    print "Line %s" % num
Line eins
Line zwei
Line drei

Überschriften

Normaler Text in ganzen Sätzen. Formatiert als Markdown: hervorgehoben fett

Hilfe und Tab-Completion

In [4]:
s="hallo welt"
#s?
#s.encode(
s.encode("base64")
Out[4]:
'aGFsbG8gd2VsdA==\n'

Dateiformat: JSON

Abspeichern als JSON, wieder einladen

Shell-Kommandos

In [5]:
!ls -l
insgesamt 10272
-rw-rw-rw-  1 dloss dloss  302868 Mai  2 14:41 Bitcoin.ipynb
-rw-rw-rw-  1 dloss dloss    1147 Mai  2 14:37 bitcoin_weighted_prices.json
drwxrwxr-x  2 dloss dloss    4096 Apr 29 18:42 bundesliga
-rw-rw-rw-  1 dloss dloss  119335 Apr  7 16:37 bundesliga.ipynb
-rw-rw-r--  1 dloss dloss  408138 Mai  2 16:28 Chapter1_Introduction.ipynb
drwxrwxr-x  7 dloss dloss   12288 Apr 29 18:42 crosscompute-tutorials
drwxrwxrwx  3 dloss dloss    4096 Mai  1 17:46 datasets
-rw-rw-rw-  1 dloss dloss 2353817 Mai  3 09:54 datenanalyse-ipython-pandas.pdf
-rw-rw-rw-  1 dloss dloss 2727936 Mai  2 15:30 datenanalyse-ipython-pandas.ppt
-rw-rw-rw-  1 dloss dloss  792146 Apr  7 17:00 E1_BEZIRK_201112.csv
-rw-rw-rw-  1 dloss dloss  225923 Nov 24 20:17 ergebnisse-1963-2010.zip
-rw-r--r--  1 dloss dloss    2048 Mai  2 15:38 foo.db
-rw-rw-rw-  1 dloss dloss    2037 Apr 20 12:59 genua-vortrag.txt
drwxrwxrwx  4 dloss dloss    4096 Mai  1 17:03 hpf
-rw-rw-rw-  1 dloss dloss  326577 Mai  2 13:58 hpf-admin.ipynb
-rw-rw-rw-  1 dloss dloss  148820 Mai  2 15:41 IPython-Demo.ipynb
-rw-rw-r--  1 dloss dloss   27092 Mai  1 16:35 ipy.vim
-rw-rw-r--  1 dloss dloss     217 Mai  3 10:14 links.txt
-rw-rw-rw-  1 dloss dloss  861410 Apr 27 21:29 mtgox.csv
-rw-rw-rw-  1 dloss dloss  861218 Mai  2 16:33 mtgoxUSD.csv
-rw-rw-rw-  1 dloss dloss  167366 Apr  7 18:28 Muenchen.ipynb
-rw-rw-r--  1 dloss dloss   21907 Mai  2 16:23 mypicture.pdf
drwxrwxr-x  6 dloss dloss    4096 Mai  1 13:25 notebooks
-rw-rw-rw-  1 dloss dloss  355731 Mai  2 15:37 OpenBSD.ipynb
drwxrwxr-x 11 dloss dloss    4096 Mai  2 10:59 other
-rw-rw-rw-  1 dloss dloss   54449 Mär 28 21:00 pandas_basics.ipynb
-rw-rw-rw-  1 dloss dloss   84604 Mär 30 21:11 Pandas Cookbook.ipynb
drwxrwxr-x  3 dloss dloss    4096 Apr 29 18:49 pandas-demo
drwxrwxr-x  3 dloss dloss    4096 Apr 29 18:53 pcap
-rw-rw-rw-  1 dloss dloss   31161 Mai  2 13:02 pcap.ipynb
-rw-rw-rw-  1 dloss dloss   26785 Mai  1 13:01 Pi.ipynb
-rw-rw-rw-  1 dloss dloss  191731 Apr 28 22:17 python-slices.graffle
-rw-rw-r--  1 dloss dloss   76393 Mai  1 16:30 stock_data.csv
drwxrwxr-x  3 dloss dloss   12288 Apr 29 18:42 tippkick
-rw-rw-r--  1 dloss dloss    7943 Mai  1 16:30 tips.csv
drwxr-xr-x  7 dloss dloss    4096 Apr 30 23:08 tutorials
-rw-rw-r--  1 dloss dloss    2267 Mai  2 16:12 Vortrag.ipynb
In [6]:
!head -20 IPython-Demo.ipynb
{
 "metadata": {
  "name": "IPython-Demo"
 },
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "print \"Hallo Welt!\""
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",

Python-Variablen übergeben

In [7]:
interface="eth0"
data = !ifconfig $interface
data.fields()
Out[7]:
[['/bin/sh:', '1:', 'ifconfig:', 'not', 'found']]
In [8]:
# Interrupt with CTRL-m i
!ping -c 6 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
From 192.168.253.1 icmp_seq=1 Destination Port Unreachable
From 192.168.253.1 icmp_seq=2 Destination Port Unreachable
From 192.168.253.1 icmp_seq=3 Destination Port Unreachable
From 192.168.253.1 icmp_seq=4 Destination Port Unreachable
From 192.168.253.1 icmp_seq=5 Destination Port Unreachable
From 192.168.253.1 icmp_seq=6 Destination Port Unreachable

--- 8.8.8.8 ping statistics ---
6 packets transmitted, 0 received, +6 errors, 100% packet loss, time 5001ms

Andere Programmiersprachen

In [9]:
%%ruby
name = "Ruby"
3.times { puts "Hallo #{ name }" }
Hallo Ruby
Hallo Ruby
Hallo Ruby
In [10]:
%%perl
# https://github.com/peelle/Perl-Euler-Solutions/blob/master/1/solution.pl
# Straight forward iteration over each number
my $sum_of_multiples = 0;
 
foreach my $number ( 1..999 ) {
# using modulus to filter
next if ( $number % 3 and $number % 5 );
$sum_of_multiples += $number;
}

print $sum_of_multiples;
233168
In [11]:
%%bash --out output --err error
echo "Zeilen:"
for i in a b c d; do echo $i; done

Stdout wurde an output übergeben:

In [12]:
print output
Zeilen:
a
b
c
d

In [13]:
%%script lua
function allwords ()
  local line = "Hallo Lua program"
  local pos = 1           -- current position in the line
  return function ()      -- iterator function
    while line do         -- repeat while there are lines
      local s, e = string.find(line, "%w+", pos)
      if s then           -- found a word?
        pos = e + 1       -- next position is after this word
        return string.sub(line, s, e)     -- return the word
      else
        line = io.read()  -- word not found; try next line
        pos = 1           -- restart from first position
      end
    end
    return nil            -- no more lines: end of traversal
  end
end


-- use example
for word in allwords() do
  print(word)
end
Hallo
Lua
program

Plotting

In [14]:
%pylab inline
Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline].
For more information, type 'help(pylab)'.
In [15]:
x = np.random.normal(size=1000)
y = np.random.normal(size=1000)
scatter(x, y, alpha=0.2)
savefig("mypicture.pdf")
In [16]:
x = np.linspace(1, 18, 100)
y = x[:, np.newaxis]
im = y * np.sin(x) 
plt.imshow(im, cmap=matplotlib.cm.gray)
Out[16]:
<matplotlib.image.AxesImage at 0x2c99850>
In [17]:
%load http://matplotlib.org/mpl_examples/api/radar_chart.py
In [ ]:
"""
Example of creating a radar chart (a.k.a. a spider or star chart) [1]_.

Although this example allows a frame of either 'circle' or 'polygon', polygon
frames don't have proper gridlines (the lines are circles instead of polygons).
It's possible to get a polygon grid by setting GRIDLINE_INTERPOLATION_STEPS in
matplotlib.axis to the desired number of vertices, but the orientation of the
polygon is not aligned with the radial axes.

.. [1] http://en.wikipedia.org/wiki/Radar_chart
"""
import numpy as np

import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.spines import Spine
from matplotlib.projections.polar import PolarAxes
from matplotlib.projections import register_projection


def radar_factory(num_vars, frame='circle'):
    """Create a radar chart with `num_vars` axes.

    This function creates a RadarAxes projection and registers it.

    Parameters
    ----------
    num_vars : int
        Number of variables for radar chart.
    frame : {'circle' | 'polygon'}
        Shape of frame surrounding axes.

    """
    # calculate evenly-spaced axis angles
    theta = 2*np.pi * np.linspace(0, 1-1./num_vars, num_vars)
    # rotate theta such that the first axis is at the top
    theta += np.pi/2

    def draw_poly_patch(self):
        verts = unit_poly_verts(theta)
        return plt.Polygon(verts, closed=True, edgecolor='k')

    def draw_circle_patch(self):
        # unit circle centered on (0.5, 0.5)
        return plt.Circle((0.5, 0.5), 0.5)

    patch_dict = {'polygon': draw_poly_patch, 'circle': draw_circle_patch}
    if frame not in patch_dict:
        raise ValueError('unknown value for `frame`: %s' % frame)

    class RadarAxes(PolarAxes):

        name = 'radar'
        # use 1 line segment to connect specified points
        RESOLUTION = 1
        # define draw_frame method
        draw_patch = patch_dict[frame]

        def fill(self, *args, **kwargs):
            """Override fill so that line is closed by default"""
            closed = kwargs.pop('closed', True)
            return super(RadarAxes, self).fill(closed=closed, *args, **kwargs)

        def plot(self, *args, **kwargs):
            """Override plot so that line is closed by default"""
            lines = super(RadarAxes, self).plot(*args, **kwargs)
            for line in lines:
                self._close_line(line)

        def _close_line(self, line):
            x, y = line.get_data()
            # FIXME: markers at x[0], y[0] get doubled-up
            if x[0] != x[-1]:
                x = np.concatenate((x, [x[0]]))
                y = np.concatenate((y, [y[0]]))
                line.set_data(x, y)

        def set_varlabels(self, labels):
            self.set_thetagrids(theta * 180/np.pi, labels)

        def _gen_axes_patch(self):
            return self.draw_patch()

        def _gen_axes_spines(self):
            if frame == 'circle':
                return PolarAxes._gen_axes_spines(self)
            # The following is a hack to get the spines (i.e. the axes frame)
            # to draw correctly for a polygon frame.

            # spine_type must be 'left', 'right', 'top', 'bottom', or `circle`.
            spine_type = 'circle'
            verts = unit_poly_verts(theta)
            # close off polygon by repeating first vertex
            verts.append(verts[0])
            path = Path(verts)

            spine = Spine(self, spine_type, path)
            spine.set_transform(self.transAxes)
            return {'polar': spine}

    register_projection(RadarAxes)
    return theta


def unit_poly_verts(theta):
    """Return vertices of polygon for subplot axes.

    This polygon is circumscribed by a unit circle centered at (0.5, 0.5)
    """
    x0, y0, r = [0.5] * 3
    verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta]
    return verts


def example_data():
    #The following data is from the Denver Aerosol Sources and Health study.
    #See  doi:10.1016/j.atmosenv.2008.12.017
    #
    #The data are pollution source profile estimates for five modeled pollution
    #sources (e.g., cars, wood-burning, etc) that emit 7-9 chemical species.
    #The radar charts are experimented with here to see if we can nicely
    #visualize how the modeled source profiles change across four scenarios:
    #  1) No gas-phase species present, just seven particulate counts on
    #     Sulfate
    #     Nitrate
    #     Elemental Carbon (EC)
    #     Organic Carbon fraction 1 (OC)
    #     Organic Carbon fraction 2 (OC2)
    #     Organic Carbon fraction 3 (OC3)
    #     Pyrolized Organic Carbon (OP)
    #  2)Inclusion of gas-phase specie carbon monoxide (CO)
    #  3)Inclusion of gas-phase specie ozone (O3).
    #  4)Inclusion of both gas-phase speciesis present...
    data = {
        'column names':
            ['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO',
             'O3'],
        'Basecase':
            [[0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00],
             [0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00],
             [0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00],
             [0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00],
             [0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]],
        'With CO':
            [[0.88, 0.02, 0.02, 0.02, 0.00, 0.05, 0.00, 0.05, 0.00],
             [0.08, 0.94, 0.04, 0.02, 0.00, 0.01, 0.12, 0.04, 0.00],
             [0.01, 0.01, 0.79, 0.10, 0.00, 0.05, 0.00, 0.31, 0.00],
             [0.00, 0.02, 0.03, 0.38, 0.31, 0.31, 0.00, 0.59, 0.00],
             [0.02, 0.02, 0.11, 0.47, 0.69, 0.58, 0.88, 0.00, 0.00]],
        'With O3':
            [[0.89, 0.01, 0.07, 0.00, 0.00, 0.05, 0.00, 0.00, 0.03],
             [0.07, 0.95, 0.05, 0.04, 0.00, 0.02, 0.12, 0.00, 0.00],
             [0.01, 0.02, 0.86, 0.27, 0.16, 0.19, 0.00, 0.00, 0.00],
             [0.01, 0.03, 0.00, 0.32, 0.29, 0.27, 0.00, 0.00, 0.95],
             [0.02, 0.00, 0.03, 0.37, 0.56, 0.47, 0.87, 0.00, 0.00]],
        'CO & O3':
            [[0.87, 0.01, 0.08, 0.00, 0.00, 0.04, 0.00, 0.00, 0.01],
             [0.09, 0.95, 0.02, 0.03, 0.00, 0.01, 0.13, 0.06, 0.00],
             [0.01, 0.02, 0.71, 0.24, 0.13, 0.16, 0.00, 0.50, 0.00],
             [0.01, 0.03, 0.00, 0.28, 0.24, 0.23, 0.00, 0.44, 0.88],
             [0.02, 0.00, 0.18, 0.45, 0.64, 0.55, 0.86, 0.00, 0.16]]}
    return data


if __name__ == '__main__':
    N = 9
    theta = radar_factory(N, frame='polygon')

    data = example_data()
    spoke_labels = data.pop('column names')

    fig = plt.figure(figsize=(9, 9))
    fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)

    colors = ['b', 'r', 'g', 'm', 'y']
    # Plot the four cases from the example data on separate axes
    for n, title in enumerate(data.keys()):
        ax = fig.add_subplot(2, 2, n+1, projection='radar')
        plt.rgrids([0.2, 0.4, 0.6, 0.8])
        ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),
                     horizontalalignment='center', verticalalignment='center')
        for d, color in zip(data[title], colors):
            ax.plot(theta, d, color=color)
            ax.fill(theta, d, facecolor=color, alpha=0.25)
        ax.set_varlabels(spoke_labels)

    # add legend relative to top-left plot
    plt.subplot(2, 2, 1)
    labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5')
    legend = plt.legend(labels, loc=(0.9, .95), labelspacing=0.1)
    plt.setp(legend.get_texts(), fontsize='small')

    plt.figtext(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios',
                ha='center', color='black', weight='bold', size='large')
    plt.show()

Rich display

In [18]:
from IPython.core.display import Image, HTML, SVG
In [19]:
Image(filename="/usr/share/doc/texlive-doc/latex/ctable/penguin.jpg")
Out[19]:
In [20]:
SVG(filename="/usr/share/doc/ipython/examples/notebooks/python-logo.svg")
Out[20]:
image/svg+xml
In [21]:
from IPython.display import HTML
HTML('<iframe src=http://www.genua.de width=650 height=250></iframe>')
Out[21]:
In [22]:
from IPython.display import YouTubeVideo
YouTubeVideo("2G5YTlheCbw")
Out[22]:
In [23]:
import IPython
IPython.display.Math(r"\sum_{n=1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6}")
Out[23]:
$$\sum_{n=1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6}$$

LaTeX innerhalb von Markdown geht auch: $\frac{1}{\sqrt{ 2 \pi \sigma^2 }} e^{ - \frac{ (x - \mu)^2 } {2 \sigma^2} }$

Darstellungen für eigene Objekte:

In [24]:
class Disc(object):
    def __init__(self, size, color='red'):
        self.size = size
        self.color = color
        
    def _repr_svg_(self):
        return """<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
                  <circle cx="{0:d}" cy="{0:d}" r="{0:d}" fill="{1:s}" />
                  </svg>""".format(self.size, self.color)
In [25]:
Disc(65, "blue")
Out[25]:

SymPy

In [26]:
from sympy import *
%load_ext sympy.interactive.ipythonprinting
x = Symbol('x')
/usr/lib/pymodules/python2.7/mpl_toolkits/__init__.py:2: UserWarning: Module mpl_toolkits was already imported from /usr/lib/pymodules/python2.7/mpl_toolkits/__init__.pyc, but /usr/local/lib/python2.7/dist-packages is being added to sys.path
  __import__('pkg_resources').declare_namespace(__name__)
In [27]:
pi.evalf(100)
Out[27]:
$$3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068$$
In [28]:
(pi+x*2)**3
Out[28]:
$$\left(2 x + \pi\right)^{3}$$
In [29]:
((pi+x*2)**3).expand()
Out[29]:
$$8 x^{3} + 12 \pi x^{2} + 6 \pi^{2} x + \pi^{3}$$

SQL Extension

In [30]:
%load_ext sql
In [31]:
rm -rf foo.db
In [32]:
%sql sqlite:///foo.db
Out[32]:
u'Connected: [email protected]'
In [33]:
%%sql sqlite:///foo.db
CREATE TABLE writer (first_name, last_name, year_of_death);
INSERT INTO writer VALUES ('William', 'Shakespeare', 1616);
INSERT INTO writer VALUES ('Bertold', 'Brecht', 1956);
Out[33]:
$$\begin{bmatrix}\end{bmatrix}$$
In [34]:
%%sql select * from writer
Out[34]:
first_name last_name year_of_death
William Shakespeare 1616
Bertold Brecht 1956