Accessing a value in a NumPy 2D array
Start your free 7-days trial now!
To access a value in a Numpy 2D array, use the
Suppose we have the following 2D Numpy array:
x = np.array([[1,2,3], [4,5,6]])xarray([[1, 2, 3],[4, 5, 6]])
Accessing a value
To access the value residing at row 0 column 1 (i.e. the value 2):
To access the value residing at row 1 column 2 (i.e. the value 6):
Do not use
In this previous code snippet, we could have used
x instead of
x[1,2], which would also return the value 6. However, it is not good practice to use double
s in Numpy.
x involves two steps: firstly accessing row 1 (i.e.
[4,5,6]), and then accessing the 2nd index (i.e. 6). On the other hand,
x[1,2] involves just one step, that is, the value is directly fetched, and is therefore faster than double