Reshape
Lesson 9 of 18 in Coddy's Numpy Fundamentals course.
We can create powerful arrays with the reshape method.
The syntax is: np.reshape(ary, newshape)
the reshape changes the shape of the array. the new shape is a tuple or a list that must be the same multiplication result as the old shape
For example: old shape: (2, 5), multiplication result: 2*5=10, the new shape can be any combination of numbers as long as the multiplication is 10, meaning the new shape can be either one of: (1, 10) , (10, 1) , (5, 2)
Example 1
ary = np.arange(10) # --> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
ary = np.reshape(ary, (5, 2))
>>> [[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]]Example 2
ary = np.zeros(6) # --> [0., 0., 0., 0., 0., 0.]
ary = np.reshape(ary, (2, 3))
>>> [[0., 0., 0.],
[0., 0., 0.]]Exmaple 3
Reshape to higher dimensions
ary = np.arange(12)
ary = np.reshape(ary, (2, 3, 2))
>>> [[[ 0, 1],
[ 2, 3],
[ 4, 5]],
[[ 6, 7],
[ 8, 9],
[10, 11]]]
Challenge
EasyCreate a numpy array that contains incrementing elements from 1 to 200(including): [1, 2, 3, 4, 5, 6, ..., 200]
and reshape it to a (20, 10) shape
Try it yourself
import numpy as np
print(ary)All lessons in Numpy Fundamentals
2N-Dimensional Array Creation
Higher DimensionUnderstanding ShapesPopulate with Fixed ValuesNumpy TypesRangeReshape