Motivation:
%%javascript
$.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js')
import numpy as np
# convert list to array
x = np.array([1, 2, 3, 4, 5])
2 * x
x**2
x**x
np.cos(x)
Achtung: Man brauch die cos
Methode aus numpy!
import math
math.cos(x)
Bei großen Datensätzen ist die Laufzeit relevant:
%%timeit
xs = [42] * 10000
xs2 = [x**2 for x in xs]
%%timeit
x = np.full(10000, 42)
x2 = x**2
Selbstgeschriebene Funktionen, die nur für eine Zahl geschrieben wurden, funktionieren oft ohne Änderung mit Arrays!
def poly(y):
return y + 2 * y**2 - y**3
poly(x)
poly(np.pi)
# this also works:
def poly(x):
return x + 2 * x**2 - x**3
poly(x)
Das erlaubt es einem unter anderem, sehr leicht physikalische Formeln auf seine Datenpunkte anzuwenden.
Arrays können beliebige Dimension haben:
# two-dimensional array
y = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
y + y
Das erlaubt es z.B. eine ganze Tabelle als ein Array abzuspeichern.
Mit Arrays sind auch Matrixoperationen möglich:
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])
In Numpy werden Dimensionen auch Achsen genannt.
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}')
Es gibt viele nützliche Funktionen, die bei der Erstellung von Arrays helfen:
np.zeros(10)
np.ones((5, 2))
np.linspace(0, 1, 11)
# like range() for arrays:
np.arange(0, 10)
np.logspace(-4, 5, 10)
Numpy erlaubt einem sehr bequem bestimmte Elemente aus einem Array auszuwählen
x = np.arange(0, 10)
print(x)
# like lists:
x[4]
# all elements with indices ≥1 and <4:
x[1:4]
# negative indices count from the end
x[-1], x[-2]
# combination:
x[3:-2]
# step size
x[::2]
# trick for reversal: negative step
x[::-1]
y = np.array([x, x + 10, x + 20, x + 30])
y
# comma between indices
y[3, 2:-1]
# only one index ⇒ one-dimensional array
y[2]
# other axis: (: alone means the whole axis)
y[:, 3]
# inspecting the number of elements per axis:
y.shape