Search⌘ K

Indexing in NumPy

Explore the fundamentals of indexing in NumPy arrays to efficiently access and manipulate multi-dimensional data. Learn how to retrieve single values, rows, columns, subsets, and specific elements from grids, and understand how to arrange and extract values using advanced indexing techniques.

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 │
   └───┴───┴───┘
Python 3.5
import numpy as np
Z = 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)
   └───┴───┗━━━┛   ┗━━━┛
Python 3.5
import numpy as np
Z = 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)
   └───┴───┴───┘
Python 3.5
import numpy as np
Z = 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 the second column from a grid, use ...