Indexing and Slicing NumPy Arrays in Python with Example

Indexing and slicing

Slicing data is trivial with numpy. We will slice the matrice "e". Note that, in Python, you need to use the brackets to return the rows or columns

## Slice
import numpy as np
e  = np.array([(1,2,3), (4,5,6)])
print(e)
[[1 2 3]
 [4 5 6]]

Remember with numpy the first array/column starts at 0.

## First column
print('First row:', e[0])

## Second col
print('Second row:', e[1])

Output:

First row: [1 2 3]
Second row: [4 5 6]

In Python, like many other languages,

print('Second column:', e[:,1])			
Second column: [2 5]			

To return the first two values of the second row. You use : to select all columns up to the second

## Second Row, two values
  print(e[1, :2])			
  [4 5]			

 

YOU MIGHT LIKE: