7.13 Reshaping and Transposing

We’ve used array method reshape to produce two-dimensional arrays from one-dimensional ranges. NumPy provides various other ways to reshape arrays.

reshape vs. resize

The array methods reshape and resize both enable you to change an array’s dimensions. Method reshape returns a view (shallow copy) of the original array with the new dimensions. It does not modify the original array:

In [1]: import numpy as np

In [2]: grades = np.array([[87, 96, 70], [100, 87, 90]])

In [3]: grades
Out[3]:
array([[ 87, 96, 70],
       [100, 87, 90]])

In [4]: grades.reshape(1, 6)
Out[4]: array([[ 87, 96, 70, 100, 87, 90]])

In [5]: grades
Out[5]:
array([[ 87, 96, 70],
       [100, 87, 90]])

Method resize modifies the original array’s shape:

Get Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and The Cloud 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.