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 braucht das cos
aus numpy!
import math
math.cos(x)
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.
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)
# 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