This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.

Array Slicing


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:

  1. When extracting elements from an array, specify the index, or the range of indices
  2. Specifying an index beyond the index of the last element is an error
  3. Specifying a range returns an array extracted from the existing array. Element with the end index is not included
  4. Spcifying an end index beyond the index of the last element is not an error
  5. A negative index counts the elements backwards starting from the last element

Insertion of an Element (or Array) into an Array

Just as you can extract elements from an array using slicing, it is possible to insert elements into an array. This can be done by writing an expression using slices on the left hand side of an assignment. In the following example, let us first create a one-dimensioned array with 10 elements (from 1 to 10) and then replace the first five elements with zeros.

x = np.array(range(1, 11))
print x
[ 1  2  3  4  5  6  7  8  9 10]
x[0:5] = np.zeros(5)
print x
[ 0  0  0  0  0  6  7  8  9 10]

Instead of using the function numpy.zeros(), you could use any other function that returns a one-dimensioned array with a compatible size, such as, numpy.array(), numpy.ones() etc.

Task Discussion