Manipulating array shapes
Another recurring task is flattening of arrays. Flattening in this context means transforming a multidimensional array into a one-dimensional array. In this example, we will demonstrate a number of ways to manipulate array shapes starting with flattening:
ravel()
: We can accomplish flattening with theravel()
function (see theshapemanipulation.py
file in theChapter02
folder of this book's code bundle), as shown in the following code:In: b Out: array([[[ 0, 1, 2, 3],[ 4, 5, 6, 7],[ 8, 9, 10, 11]],[[12, 13, 14, 15],[16, 17, 18, 19],[20, 21, 22, 23]]]) In: b.ravel() Out: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23])
flatten()
: The appropriately-named function,flatten()
, does the same asravel()
, butflatten()
always allocates new memory, whereasravel()
might return a view of an array. This means that we can directly manipulate the array as follows:In: b.flatten() Out: array([ 0, 1, 2, 3, 4, 5...