Common array operationsΒΆ

Now that we’ve gone through different ways of creating an array, let’s go into some of the common array operations like

import numpy as np
# an array with weight in pounds
array = np.array([140, 174, 166, 192])
array
# divide by 2.2 to get values in kilos
array / 2.2

Reshaping arraysΒΆ

Reshaping changes the dimensions of an array without modifying its data. The .reshape() method rearranges elements into a new shape, as long as the total number of elements remains the same. The .flatten() method collapses any multi-dimensional array back to one dimension. Reshaping is essential in ML workflows where models expect input data in specific shapes – for example, converting a batch of images from (height, width) to a flat feature vector.

array = np.ones((3,4))
array
array.reshape((4,3))
# reshaping has to keep the same number of items
array.reshape((12,1))
# otherwise you get into trouble
array.reshape((5,1))
# flatten arrays
print(array)
array.flatten()