numpy Array Access


Example

Slice syntax is i:j:k where i is the starting index (inclusive), j is the stopping index (exclusive) and k is the step size. Like other python data structures, the first element has an index of 0:

x = np.arange(10)
x[0]
# Out: 0

x[0:4]
# Out: array([0, 1, 2, 3])

x[0:4:2]
# Out:array([0, 2])

Negative values count in from the end of the array. -1 therefore accesses the last element in an array:

x[-1]
# Out: 9
x[-1:0:-1]
# Out: array([9, 8, 7, 6, 5, 4, 3, 2, 1])

Multi-dimensional arrays can be accessed by specifying each dimension separated by commas. All previous rules apply.

x = np.arange(16).reshape((4,4))
x
# Out: 
#     array([[ 0,  1,  2,  3],
#            [ 4,  5,  6,  7],
#            [ 8,  9, 10, 11],
#            [12, 13, 14, 15]])

x[1,1]
# Out: 5

x[0:3,0]
# Out: array([0, 4, 8])

x[0:3, 0:3]
# Out: 
#     array([[ 0,  1,  2],
#            [ 4,  5,  6],
#            [ 8,  9, 10]])

x[0:3:2, 0:3:2]
# Out: 
#     array([[ 0,  2],
#            [ 8, 10]])