Basic Indexing
Lesson 10 of 18 in Coddy's Numpy Fundamentals course.
Numpy 1-dimentional arrays can be indexed the same as python lists:
Python list indexing:
lst = [1, 2, 3, 4]
lst[1] # --> 2Numpy array indexing:
ary = np.array([1, 2, 3, 4])
ary[1] # --> 2But things get interesting with bigger dimensions .
Python 2D list indexing:
lst = [[1, 2], [3, 4]]
lst[0][1] # --> 2Numpy 2D array indexing:
ary = np.array([[1, 2], [3, 4]])
ary[0,1] # --> 2 Spot the difference: ary[0,1], lst[0][1]
We can use the same syntax of lists with Numpy arrays: ary[0][1] but it is inefficient and better to use: ary[0, 1]
ary[0][1]is less efficient because a new temporary array is created after the first index that is subsequently indexed by 1.
How to index a 3D array?
ary = np.array([
[[1], [2]],
[[3], [4]]
])
ary[0, 0, 0] # --> 1
ary[0, 1, 0] # --> 2
ary[1, 0, 0] # --> 3
ary[1, 1, 0] # --> 4This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyRetrieve the element (using indexing) that contains the value 5 from the 3D array ary
Try it yourself
import numpy as np
ary = np.array([ [ [ 0, 1 ], [ 2, 3 ] ], [ [ 4, 5 ], [ 6, 7 ] ] ])
res = ary[] # <-- Complete the indexing
print(res) # 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