Share on:

Python NumPy For Your Grandma | Section 3.3 | reshape()

December 29, 2019
python courses

This video covers NumPy’s reshape() function for restructuring the shape of a NumPy array.

Code

import numpy as np

# Suppose we have the following 1d array with 8 elements
foo = np.arange(start = 1, stop = 9)  # [1, 2, 3, 4, 5, 6, 7, 8]

# reshape into a 2x4 array using either the .reshape method of the array object, or the free function np.reshape()
bar = foo.reshape((2,4))
bar = np.reshape(a = foo, newshape = (2,4))

# slightly different interfaces
foo.reshape(2,4)  # allowed
foo.reshape(newshape = (2,4))  # error

## reshape bar from a 2x4 array to a 4x2 array
# C-style order reorders the last axis first
bar.reshape((4,2), order = 'C')

# Fortran-style order reorders the first axis first
bar.reshape((4,2), order = 'F')

# matrix transpose of bar
bar.T

# reshape foo into higher dimensions, like a 2x2x2 array
bar.reshape((2,2,2))

# reshape foo into 2x2x3 array
bar.reshape((2,2,3)) # error

# use -1 for exactly one of the newshape dimensions and numpy will calculate it for you
bar.reshape((-1, 2))

Transcript

You’ll often find yourself needing to reshape arrays. numpy makes this easy with the reshape() function. Suppose we have the following 1d array with 8 elements called foo.
We can reshape foo into a 2x4 array using either the .reshape() method of the array object, or the free function np.reshape() These methods implement the same logic, just with slightly different interfaces. With foo.reshape, we can pass in the new dimensions individually instead of as a tuple, but this comes at the expense of not being able to specify the ‘newshape’ keyword. Now let’s reshape bar from a 2x4 array to a 4x2 array. We can do this in two different orders.
First, we’ll call bar.reshape with order equal to ‘C’. This implements C-style order which reorders the last axis first.
Next, we’ll call bar.reshape with order equal to ‘F’. This implements Fortran-style order which reorders the first axis first.

You might also be interested in the matrix transpose of bar, which also happens to be a 4x2 array. You can get that with bar.T or the free function np.transpose(bar).
You can also reshape foo into higher dimensions, like a 2x2x2 array.
However, the newshape you specify must hold the same number of elements as the original array. If it doesn’t, you’ll get an error. If you’re feeling lazy, use -1 for exactly one of the newshape dimensions and numpy will calculate it for you.


Enjoyed this article? Show your support and buy some GormAnalysis merch.
comments powered by Disqus