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
Ausgewählten Elementen kann man auch direkt einen Wert zuweisen
y
y[:, 3] = 0
y
Man kann Indexing sogar gleichzeitig auf der linken und rechten Seite benutzen
y[:,0] = x[3:7]
y
Transponieren des Arrays kehrt die Reihenfolge der Indizes um:
y
y.shape
y.T
y.T.shape
Oft will man Elemente auswählen, die eine bestimmte Bedingung erfüllen.
Hierzu erstellt man zuerst eine Maske (Arrays aus True/False-Werten).
Diese kann man in eckigen Klammern übergeben.
a = np.linspace(0, 2, 11)
b = a**2
print(a)
# create a mask for all elements >= 1
mask = a >= 1
print(mask)
print(a[mask])
# do it in one step:
print(a[a>=1])
Viele Rechenoperationen reduzieren ein Array auf einen einzelnen Wert
x
y
Summe aller Elemente
np.sum(x)
Bei vielen Methoden kann die Dimension (Achse) mit angegeben werden
np.sum(y, axis=1) # sum of each row
Multiplikation aller Elemente
np.prod(x)
Mittelwert der Einträge
np.mean(x)
Standardabweichung der Einträge
np.std(x)
Fehler des Mittelwerts (geht auch einfacher):
np.std(x, ddof=1) / np.sqrt(len(x))
Schätzer der Standardabweichung
np.std(x, ddof=1)
Differenzen zwischen benachbarten Elementen
z = x**2
print('z ', z)
np.diff(z)
Einlesen aus Textdateien: genfromtxt
Sie gibt den Inhalt einer Textdatei als Array zurück.
Das Gegenstück ist savetxt
.
n = np.arange(11)
x = np.linspace(0, 1, 11)
np.savetxt('test.txt', [n, x])
# see exercise 1-python/6-readwrite
with open('test.txt', 'r') as f:
print(f.read())
data = np.array([n, x])
np.savetxt('test.txt', np.column_stack([n, x]))
with open('test.txt', 'r') as f:
print(f.read())
Man sollte aber immer erklären, was man da abspeichert:
n = np.arange(11)
x = np.linspace(0, 1, 11)
# header schreibt eine Kommentarzeile in die erste Zeile der Datei
np.savetxt('test.txt', np.column_stack([n, x]), header="n x")
with open('test.txt', 'r') as f:
print(f.read())
Einlesen der Werte mit genfromtxt
:
a, b = np.genfromtxt('test.txt', unpack=True)
a, b
Um die Datentypen zu erhalten, muss fmt
angegeben werden:
np.savetxt(
'test.txt',
np.column_stack([n, x]),
fmt=['%d', '%.4f'], # first column integer, second 4 digits float
delimiter=',',
header='n,x',
)
data = np.genfromtxt(
'test.txt',
dtype=None, # guess data types
delimiter=',',
names=True,
)
data ist ein besonderes array, das sich ähnlich wie ein dict
verhält:
data
data['n'], data.shape, data.dtype