Array Slicing [Sept. 6, 2012, 12:40 p.m.]
Extrcation of Elements or Arrays from an Array
Given an array, it is possible to copy elements (or contiguous parts of it) into another variable (or array). To do so, we must refer to the index (or indices) of the element. The number of indices required is the same as the number of dimensions of the array.
Slicing One-dimensioned Arrays
Let us first create a one-dimensioned array and copy an element of it. In Python, indexing starts with 0.
import numpy as np
x = array([1, 2, 3, 4, 5,6, 7, 8])
print x
[ 1 2 3 4 5 6 7 8]
a = x[0]
print a
1
b = x[0:4]
print b
[ 1 2 3 4]
c = x[:4] # Same as x[0:4]
print c
[ 1 2 3 4]
print x[-1]
8
print x[-3:-1]
[ 6 7]
Here are some points to remember when you want to slice arrays:
- When extracting elements from an array, specify the index, or the range of indices
- Specifying an index beyond the index of the last element is an error
- Specifying a range returns an array extracted from the existing array. Element with the end index is not included
- Spcifying an end index beyond the index of the last element is not an error
- A negative index counts the elements backwards starting from the last element