Querying and changing the shape of an array
Since we have learnt various ways to create an array, we can now definitely learn how to query and change the shape of an array.
How to do it...
The shape of an array is stored in the shape
field of the ndarray
object, as shown in the following example:
x = np.array([[1,2,3,4,5,6],[7,8,9,10,11,12]]) x.shape
The shape
field of an ndarray
object contains a tuple with the size of each of the dimensions of the array, so the preceding code will produce the following output:
(2, 6)
It is possible to assign a to the field shape, which has the effect of reshaping the array, as shown in the following example:
x.shape = (4,3)
This statement will change the array to the following:
array([[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10, 11, 12]])