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. ...

Get Python Data Science Essentials - Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.