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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.