Indexing in NumPy
This lesson will help you learn indexing in NumPy.
Indexing means to refer to any value in an array. Each item in a numpy array is stored at a specific index. To access value at a specific index write:
Z=np.arrange(9)
Z[0] #get the value at index 0
Get the First Value
To get the first value of a matrix, write: Z[0,0]
.
┏━━━┓───┬───┐ ┏━━━┓
┃ 0 ┃ 1 │ 2 │ → ┃ 0 ┃ (scalar)
┗━━━┛───┼───┤ ┗━━━┛
Z │ 3 │ 4 │ 5 │
├───┼───┼───┤
│ 6 │ 7 │ 8 │
└───┴───┴───┘
Press + to interact
import numpy as npZ = np.arange(9).reshape(3,3)print(Z[0,0])
Get the Last Value
To get the last value of a matrix, write: Z[-1,-1]
.
┌───┬───┬───┐
│ 0 │ 1 │ 2 │
├───┼───┼───┤
Z │ 3 │ 4 │ 5 │
├───┼───┏━━━┓ ┏━━━┓
│ 6 │ 7 ┃ 8 ┃ → ┃ 8 ┃ (scalar)
└───┴───┗━━━┛ ┗━━━┛
Press + to interact
import numpy as npZ = np.arange(9).reshape(3,3)print(Z[-1,-1])
Get a row from a Grid
To get a row from a grid, write: Z[row_index
].
To get the first row from a grid, write: Z[1]
.
┌───┬───┬───┐
│ 0 │ 1 │ 2 │
┏━━━┳━━━┳━━━┓ ┏━━━┳━━━┳━━━┓
Z ┃ 3 ┃ 4 ┃ 5 ┃ → ┃ 3 ┃ 4 ┃ 5 ┃
┗━━━┻━━━┻━━━┛ ┗━━━┻━━━┻━━━┛
│ 6 │ 7 │ 8 │ (view)
└───┴───┴───┘
Press + to interact
import numpy as npZ = np.arange(9).reshape(3,3)print(Z[1])
Get a Column from a Grid
To get the column from a grid, use
Z[:,column_index]
To get ...
Access this course and 1400+ top-rated courses and projects.