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

# Reshaping Arrays

The shape of an existing array can be modified as long as the new shape is compatible with the existing shape. That is, the number of elements of the new shape must be the same as the number of elements of the existing shape.

At this point, let me also introduce the function range() which creates a list of integer values starting at a specified value and incrementing by one each time until a specified ending value is reached (ending value not included in the range). We will then reshape the list into a two-dimensioned numpy.ndarray using the numpy.reshape() function.

a = range(1, 13)
print type(a)
<type 'list'>
print a
[1 2 3 4 5 6 7 8 9 10 11 12]
b = reshape(a, (3,4))
print type(b)
<type 'numpy.ndarray'>
print b
[[1  2  3  4]
[5  6  7  8]
[9 10 11 12]]
x = range(1, 25)
y = reshape(x, (2, 3, 4))
print y
[[[ 1  2  3  4]
[ 5  6  7  8]
[ 9 10 11 12]]

[[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]]
z = numpy.reshape(y, (6, 4))
print z
[[ 1  2  3  4]
[ 5  6  7  8]
[ 9 10 11 12]
[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]

The reshape() function takes as input a container such as a list or numpy.ndarray and returns a reshaped numpy.ndarray. If the number of elements in the original container is not the same as the number of elements in the reshaped array, it is an error.