Manipulating array shapes
We have already learned about the reshape()
function. Another repeating chore is the flattening of arrays. Flattening in this setting entails transforming a multidimensional array into a one-dimensional array. The code for this example is in the shapemanipulation.py
file in this book's code bundle.
import numpy as np # Demonstrates multi dimensional arrays slicing. # # Run from the commandline with # # python shapemanipulation.py print "In: b = arange(24).reshape(2,3,4)" b = np.arange(24).reshape(2,3,4) print "In: b" print 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]]]) print "In: b.ravel()" print 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]) print "In: b.flatten()" print b.flatten() #Out: #array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,...