Reshaping
Reshaping Arrays¶
There are many different ways to change the dimensions of an array. To begin with there is flatten which will take any array and turn it into a one dimensional array. For example, look what happens to the sales array. With flatten, you can compare where the numbers are with flatten versus in the array.
#Print the flattened array
print(sales.flatten())
#Compare to the original array
print(sales)
Reshaping is a way to transform between different dimensions. First, the array is flattened to a one dimensional array then it fills in an array of the shape specified. Take this six element 1d array to begin with.
#Create the data
ar = np.array([1, 2, 3, 4, 5, 6])
print(ar)
To use reshape, you must pass a tuple of dimensions to use. The multiplication of these dimensions must be equal to the overall number of elements in the array. For example, the shape 3x2 works because there are 6 total elements. This will return an array with 3 rows and 2 columns.
#Reshape the array
print(ar.reshape((3,2)))
Of course, we could just as well have a 2x3 array instead...
print(ar.reshape((2,3)))
You can also have higher dimension arrays with re-shaping. For example, we might want a 3x2x2 from a length 12 one dimensional array.
#Create data
ar = np.array(list(range(1,13)))
print(ar)
print()
#Print re-shaped data
print(ar.reshape((3,2,2)))
Reshaping can be applied however you need it to be done and will allow for many useful applications. One last example will be bringing back the sales data. You might imagine a scenario where all you care about is seeing the sales numbers across days easily. In that case, it might be useful to just transform the array to show a one dimensional array per day referring to the sales numbers....
print("Original Sales Data:")
print(sales)
print()
print("Reshaped Sales Data")
print(sales.reshape(3,4))