Array Manipulation Functions
Contents
Array Manipulation Functions#
NumPy comes with lots of functions for manipulating arrays. Some of them are needed more often, others almost never. A comprehensive list is provided in array manipulation routines. Here we only mention some of the more important ones.
import numpy as np
Modifying Shape with reshape
#
A NumPy array’s reshape
method yields an array of different shape, but with identical data. The new array has to have the same number of elements as the old one.
a = np.ones(5) # 1d (vector)
b = a.reshape(1, 5) # 2d (row matrix)
c = a.reshape(5, 1) # 2d (column matrix)
print(a, '\n')
print(b, '\n')
print(c)
[1. 1. 1. 1. 1.]
[[1. 1. 1. 1. 1.]]
[[1.]
[1.]
[1.]
[1.]
[1.]]
One dimension may be replaced by -1
indicating that the size of this dimension shall be computed by NumPy:
a = np.ones((8, 8))
b = a.reshape(4, -1)
print(a.shape, b.shape)
(8, 8) (4, 16)
Mirrowing with fliplr
and flipud
#
To mirrow a 2d array on its vertical or horizontal axis use fliplr
and flipud
, respectively.
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.fliplr(a)
print(a, '\n')
print(b)
[[1 2 3]
[4 5 6]]
[[3 2 1]
[6 5 4]]
Joining Arrays with concatenate
and stack
#
Arrays of identical shape (except for one axis) may be joined along an existing axis to one large array with concatenate
.
a = np.ones((2, 3))
b = np.zeros((2, 5))
c = np.full((2, 2), 5)
d = np.concatenate((a, b, c), axis=1)
print(d)
[[1. 1. 1. 0. 0. 0. 0. 0. 5. 5.]
[1. 1. 1. 0. 0. 0. 0. 0. 5. 5.]]
If identically shaped array shall be joined along a new axis, use stack
.
a = np.ones(2)
b = np.zeros(2)
c = np.full(2, 5)
d = np.stack((a, b, c), axis=1)
print(d)
[[1. 0. 5.]
[1. 0. 5.]]
Appending Data with append
#
Like Python lists NumPy arrays may be extended by appending further data. The append
method takes the original array and the new data and returns the extended array.
a = np.ones((3, 3))
b = np.append(a, [[1, 2, 3]], axis=0)
print(b)
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]
[1. 2. 3.]]