Manipulate your dataset with Numpy's indexing and slicing capabilities.
Indexing and Slicing in Numpy

Indexing and slicing

Numpy follows Python's rules

  • Includes the first
  • Excludes the last
In [1]:
import numpy as np
In [4]:
# Create array
lst = [1, 4, 5, 8]
array = np.array(lst, float)
array
Out[4]:
array([ 1.,  4.,  5.,  8.])
In [5]:
# access second element
array[1]
Out[5]:
4.0
In [6]:
# access from first to second
array[: 2]
Out[6]:
array([ 1.,  4.])
In [7]:
# access from second to last
array[1:]
Out[7]:
array([ 4.,  5.,  8.])
In [10]:
# 2D array
lst_2 = [[1, 2, 3], [4, 5, 6]]
array = np.array(lst_2, float)
array
Out[10]:
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.]])
In [11]:
# row 1, all columns
array[1, :]
Out[11]:
array([ 4.,  5.,  6.])
In [12]:
# row 0, column 0 to 1
# as mentioned previously, numpy includes the first, and excludes the last
# so you need to use :2 to reach 1
array[0, :2]
Out[12]:
array([ 1.,  2.])
Tags: numpy