Slicing
Lesson 11 of 18 in Coddy's Numpy Fundamentals course.
Slicing in numpy is the same as slicing with lists.
The basic slicing syntax is: ary[start:stop:step]
Example 1
Start from index 1 and take elements by jumping 2 steps and stop at the last index (not including):
ary = np.array([0, 1, 2, 3, 4, 5])
print(ary[1:-1:2])
>>> [1 3]Example 2
Same as above but with higher dimensions
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]]]Note: Empty start and Empty end are also supported in numpy
ary = np.array([0, 1, 2, 3, 4, 5])
ary[:2] # --> [0 1]
ary[3:] # --> [3 4 5]Challenge
Slice [[1,2],[3,4]] and [[9,10], [11,12]] from the ary
Save the result in the res variable and print res
Try it yourself
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
All lessons in Numpy Fundamentals
2N-Dimensional Array Creation
Higher DimensionUnderstanding ShapesPopulate with Fixed ValuesNumpy TypesRangeReshape3Indexing Numpy Array
Basic IndexingSlicingArray IndexingDimensional IndexingBoolean IndexingMultiple Condition Indexing