Reshaping arrays
NumPy makes it simple to change the shape of your arrays. Earlier in this chapter, we briefly saw the .reshape() method of the NumPy array and how it can be used to reshape a one-dimensional array into a matrix. It is also possible to convert from a matrix back to an array. The following example demonstrates this by creating a nine-element array, reshaping it into a 3 x 3 matrix, and then back to a 1 x 9 array:
In [47]: # create a 9 element array (1x9) a = np.arange(0, 9) # and reshape to a 3x3 2-d array m = a.reshape(3, 3) m Out[47]: array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) In [48]: # and we can reshape downward in dimensions too reshaped = m.reshape(9) reshaped Out[48]: array([0, 1, 2, 3, 4, 5, 6, 7, 8])
Note
Note that .reshape() returns a new array with a different shape. The original array's shape remains unchanged.
The .reshape() method is not the only means of reorganizing data. Another means is the .ravel() method...