Numpy

  • Numpy steht für Numerical Python und ist die Grundlage für wissenschaftliche Datenverarbeitung
  • Stellt viele algebraische Methoden zur Verfügung

Motivation:

  • Meist hat man nach in einer Auswertung Datenpunkte, die verarbeitet werden müssen
  • Numpy ist eine Python-Bibliothek, die den Umgang mit Datenpunkten enorm vereinfacht
In [1]:
%%javascript
$.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js')

Inhalt¶

Grundlagen¶

In [2]:
import numpy as np
  • Grunddatentyp von Numpy: das Array
  • Kann man sich als effizientere Liste vorstellen
  • Idee von Numpy: Man kann ein Array ähnlich wie eine Zahl verwenden. Operationen werden dann auf allen Elementen ausgeführt
  • Am besten versteht man das mit einigen Beispielen:
In [3]:
# convert list to array
x = np.array([1, 2, 3, 4, 5])
In [4]:
2 * x
Out[4]:
array([ 2,  4,  6,  8, 10])
In [5]:
x**2
Out[5]:
array([ 1,  4,  9, 16, 25])
In [6]:
x**x
Out[6]:
array([   1,    4,   27,  256, 3125])
In [7]:
np.cos(x)
Out[7]:
array([ 0.54030231, -0.41614684, -0.9899925 , -0.65364362,  0.28366219])

Achtung: Man brauch die cos Methode aus numpy!

In [8]:
import math
math.cos(x)
-------------------------------------------------------------------
TypeError                         Traceback (most recent call last)
<ipython-input-8-87cdf88e21ce> in <module>
      1 import math
----> 2 math.cos(x)

TypeError: only size-1 arrays can be converted to Python scalars

Bei großen Datensätzen ist die Laufzeit relevant:

In [9]:
%%timeit
xs = [42] * 10000
xs2 = [x**2 for x in xs]
1.62 ms ± 26.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [10]:
%%timeit 
x = np.full(10000, 42)
x2 = x**2
9.35 µs ± 148 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Selbstgeschriebene Funktionen, die nur für eine Zahl geschrieben wurden, funktionieren oft ohne Änderung mit Arrays!

In [11]:
def poly(y):
    return y + 2 * y**2 - y**3

poly(x)
Out[11]:
array([  2,   2,  -6, -28, -70])
In [12]:
poly(np.pi)
Out[12]:
-8.125475224531307
In [13]:
# this also works:
def poly(x):
    return x + 2 * x**2 - x**3

poly(x)
Out[13]:
array([  2,   2,  -6, -28, -70])

Das erlaubt es einem unter anderem, sehr leicht physikalische Formeln auf seine Datenpunkte anzuwenden.

Arrays können beliebige Dimension haben:

In [14]:
# two-dimensional array
y = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

y + y
Out[14]:
array([[ 2,  4,  6],
       [ 8, 10, 12],
       [14, 16, 18]])

Das erlaubt es z.B. eine ganze Tabelle als ein Array abzuspeichern.

Mit Arrays sind auch Matrixoperationen möglich:

In [15]:
A = np.array([[1,1],
              [0,1]])
B = np.array([[2,0],
              [3,4]])

# element-wise product
print(A * B)

# matrix product
print(A @ B)

# also with one-dimensional vectors
np.array([1, 2, 3]) @ np.array([4, 5, 6])
[[2 0]
 [0 4]]
[[5 4]
 [3 4]]
Out[15]:
32

Dimension von Arrays¶

In Numpy werden Dimensionen auch Achsen genannt.

In [16]:
a = np.array([1.5, 3.0, 4.2])
b = np.array([[1, 2], [3, 4]])

print(f'Array a \n a.ndim   {a.ndim} \n a.shape  {a.shape} \n a.size   {a.size} \n a.dtype  {a.dtype}')
print(f'Array b \n b.ndim   {b.ndim} \n b.shape  {b.shape} \n b.size   {b.size} \n b.dtype  {b.dtype}')
Array a 
 a.ndim   1 
 a.shape  (3,) 
 a.size   3 
 a.dtype  float64
Array b 
 b.ndim   2 
 b.shape  (2, 2) 
 b.size   4 
 b.dtype  int64

Erstellen von Arrays¶

Es gibt viele nützliche Funktionen, die bei der Erstellung von Arrays helfen:

In [17]:
np.zeros(10)
Out[17]:
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
In [18]:
np.ones((5, 2))
Out[18]:
array([[1., 1.],
       [1., 1.],
       [1., 1.],
       [1., 1.],
       [1., 1.]])
In [19]:
np.linspace(0, 1, 11)
Out[19]:
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
In [20]:
# like range() for arrays:
np.arange(0, 10)
Out[20]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [21]:
np.logspace(-4, 5, 10)
Out[21]:
array([1.e-04, 1.e-03, 1.e-02, 1.e-01, 1.e+00, 1.e+01, 1.e+02, 1.e+03,
       1.e+04, 1.e+05])

Numpy Indexing¶

Numpy erlaubt einem sehr bequem bestimmte Elemente aus einem Array auszuwählen

In [22]:
x = np.arange(0, 10)
print(x)

# like lists:
x[4]
[0 1 2 3 4 5 6 7 8 9]
Out[22]:
4
In [23]:
# all elements with indices ≥1 and <4:
x[1:4]
Out[23]:
array([1, 2, 3])
In [24]:
# negative indices count from the end
x[-1], x[-2]
Out[24]:
(9, 8)
In [25]:
# combination:
x[3:-2]
Out[25]:
array([3, 4, 5, 6, 7])
In [26]:
# step size
x[::2]
Out[26]:
array([0, 2, 4, 6, 8])
In [27]:
# trick for reversal: negative step
x[::-1]
Out[27]:
array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])

Indexing1D

In [28]:
y = np.array([x, x + 10, x + 20, x + 30])
y
Out[28]:
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35, 36, 37, 38, 39]])
In [29]:
# comma between indices
y[3, 2:-1]
Out[29]:
array([32, 33, 34, 35, 36, 37, 38])
In [30]:
# only one index ⇒ one-dimensional array
y[2]
Out[30]:
array([20, 21, 22, 23, 24, 25, 26, 27, 28, 29])
In [31]:
# other axis: (: alone means the whole axis)
y[:, 3]
Out[31]:
array([ 3, 13, 23, 33])
In [32]:
# inspecting the number of elements per axis:
y.shape
Out[32]:
(4, 10)