%%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)
Bei großen Datensätzen relevant: Laufzeit!
%%timeit
xs = [42] * 100000
xs2 = [x**2 for x in xs]
%%timeit
x = np.full(100000, 42)
x2 = x**2
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.
a = np.array([1.5, 3.0, 4.2])
b = np.array([[1, 2], [3, 4]])
print(a.ndim, a.shape, a.size, a.dtype)
print(b.ndim, b.shape, b.size, 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)
# 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 >= 1)
print(a[a >= 1])
Viele Rechenoperationen reduzieren ein Array auf einen einzelnen Wert
x
np.sum(x)
np.prod(x)
np.mean(x)
Standardabweichung
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
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