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])
[ 1 2 3 4 5 6 7 8]
a = x
b = x[0:4]
[ 1 2 3 4]
c = x[:4] # Same as x[0:4]
[ 1 2 3 4]
[ 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
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))
[ 1 2 3 4 5 6 7 8 9 10]
x[0:5] = np.zeros(5)
[ 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.