Resizing arrays

Earlier, we mentioned how you can change the type of the elements of an array. We will now shortly stop for a while to examine the most common instructions to modify the shape of an existing array.

Let's start with an example that uses the .reshape method, which accepts an n-tuple containing the size of the new dimensions as a parameter:

In: import numpy as np
# Restructuring a NumPy array shape
original_array = np.array([1, 2, 3, 4, 5, 6, 7, 8])
Array_a = original_array.reshape(4,2)
Array_b = original_array.reshape(4,2).copy()
Array_c = original_array.reshape(2,2,2)
# Attention because reshape creates just views, not copies
original_array[0] = -1

Our original array is a unidimensional vector of integer numbers from 1 to 8. Here is what we execute in the code:

  1. We assign Array_a to a reshaped original_array of size 4 x 2
  2. We do the same with Array_b, though we append the .copy() method, which will copy the array into a new one
  3. Finally, we assign Array_c to a reshaped array in three dimensions of size 2 x 2 x 2
  4. After having done such an assignment, the first element of original_array is changed in value from 1 to -1

 

Now, if we check the content of our arrays, we will notice that Array_a and Array_c, though they have the desired shape, are characterized by -1 as the first element. That's because they dynamically mirror the original array they are in view from:

In: Array_a

Out: array([[-1, 2],
[3, 4],
[5, 6],
[7, 8]])

In: Array_c

Out: array([[[-1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])

Only the Array_b array, having been copied before mutating the original array, has a first element with a value of 1:

In: Array_b

Out: array([[1, 2],
[3, 4],
[5, 6],
[7, 8]])

If it is necessary to change the shape of the original array, then the resize method is to be favored:

In: original_array.resize(4,2) 
original_array

Out: array([[-1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8]])

The same results may be obtained by acting on the .shape value by assigning a tuple of values representing the size of the intended dimensions:

In: original_array.shape = (4,2)  

Instead, if your array is two-dimensional and you need to exchange the rows with the columns, that is, to transpose the array, the .T or .transpose() methods will help you obtain such a kind of transformation (which is a view, like .reshape):

In: original_array

Out: array([[-1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8]])
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset