When an Numpy array is created, its elements can be returned by indexing. Indexing of array elements is implemented by using brackets. If there are several non contiguous elements to be indexed, a list of indices should be appended. Similar as for Python list, negative indexing represents indexing number from the end of an Numpy array. If you want to return parts of an array and assign to a new array, this is called slicing. While slicing a Python list is a copy of the corresponding part of a list, slicing of Numpy array is the view of the original array, which is quite different. Next code examples show working with indexing and slicing of Numpy arrays.
#Import Numpy module
import numpy as np
#create an one-dimensional array of length 10
x = np.arange(1, 11)
x
#output
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
#return the 9th element
x[8]
#Out
9
#Indexing using negative symbol
#the last element of Numpy array
x[-1]
#Out
10
#the third last element of an array
x[-3]
#Out
8
#Using colon for contiguous indexing
#return second to fourth elements of array
x[1:4]
#Output
array([2, 3, 4])
#non contiguous indexing of array
x[[5, 7, 9]]
#Out
array([ 6, 8, 10])
#a two-dimensional array of shape (2,4)
B = np.arange(1, 9).reshape((2, 4))
B
#output
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
#indexing the element at second row, fourth column of array
B[1, 3]
#Output
8
#Create an array of shape(3,3)
C = np.arange(1, 10).reshape((3, 3))
C
#Output
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
#return second row all column of array
C[1, :]
#result
array([4, 5, 6])
#return all rows, third column of array
C[:, 2]
#Output
array([3, 6, 9])
#return first three rows, and first and second columns
C[0:3, 0:2]
#Output
array([[1, 2],
[4, 5],
[7, 8]])
#return first and second rows, first and second columns of array
C[[1, 2], 1:3]
#Output
array([[5, 6],
[8, 9]])
0 Comments