Menu
Coddy logo textTech

Slicing

Lektion 11 von 18 im Kurs Numpy Grundlagen von Coddy.

Slicing in NumPy funktioniert genauso wie das Slicing bei Listen.

Die grundlegende Slicing-Syntax lautet: ary[start:stop:step]

 

Beispiel 1 

Beginne bei Index 1, nimm Elemente in Schritten von 2 und stoppe beim letzten Index (nicht inklusive):

ary = np.array([0, 1, 2, 3, 4, 5])
print(ary[1:-1:2])
>>> [1 3]

Beispiel 2

Genauso wie oben, aber mit höheren Dimensionen

ary = np.array([[[1,2],[3,4]], [[5,6],[7,8]], [[9,10], [11,12]]]) # <-- Shape: (3, 2, 2)
print(ary[1:-1:2])
>>> [[[5 6]
>>>  [7 8]]]

Hinweis: Leere Start- und Endwerte werden in NumPy ebenfalls unterstützt

ary = np.array([0, 1, 2, 3, 4, 5])
ary[:2] # --> [0 1]
ary[3:] # --> [3 4 5]
challenge icon

Aufgabe

Slicen Sie [[1,2],[3,4]] und [[9,10], [11,12]] aus dem ary

Speichern Sie das Ergebnis in der Variable res und geben Sie res aus

Probier es selbst

import numpy as np
ary = np.array([ [ [ 1,2 ],[ 3,4 ] ], [ [ 5,6 ],[ 7,8 ] ], [ [ 9,10 ], [ 11,12 ] ] ]) # Don't touch
res = ary[] # <-- Slice
print(str(res).replace('\n', '')) # Don't touch

Alle Lektionen in Numpy Grundlagen