11-785 Spring 2023 Recitation 0B: Fundamentals of NumPy (Part 3/8)

We’re going to be looking at pivoting data and more specifically reshaping numpy arrays. So what is a reshape operation? A reshape operation is used to change the shape of a numpy array without altering the values or the number of elements in the array. So we’re first going to look at reshaping within the same number of dimensions. So let’s look at an example. Suppose we have a numpy array with a shape 3, 4, 5. We can look at the size of the array, which comes out to be 60. We can also get this value by multiplying the dimensions of the array, which is 3 into 4 into 5. So on printing this array, we can see that this array has three batches. And each batch has a numpy array of shape 4, 5, which means that each batch has four rows and five columns. Now let’s reshape this array into the shape of 2, 6, 5. On printing this array, we can see that this array has two batches. And each batch is a numpy array of the shape 6, 5. All the while maintaining the exact same values and the same number of elements as our previous array. So we’re now going to talk about reshaping to a different number of dimensions. So suppose we have an array with 120 elements, we have created this array using the numpy.arrange function, which will create an array with elements from 0 to 119, as seen over here. So now let’s reshape this array into an array of shape 3, 4, 10. We can see that the number of elements in this newly reshaped array will still be the same as 3 into 4 into 10 is still 120, which is the same number of elements as the number of elements in the original array. And as we can see, this reshaped array has three batches. And each batch has a shape of 4, 10. Now let’s look at a different example where we reshape our array that had shape 3, 4, 10 into an array of shape 6, 20. We can see that our previous array has been reshaped into an array, which has six separate batches, where each batch has 20 elements. But your array runs off now.

AI video(s) you might be interested in …